jQuery选择器继承了CSS与Path语言的部分语法,允许通过标签名、属性名或内容对DOM元素进行快速、准确的选择,而不必担心浏览器的兼容性,通过jQuery选择器对页面元素的精准定位,才能完成元素属性和行为的处理。
比较常见的选择器 比如:
1).$("#id名"):代替document.getElementById(“id”);
当点击一个按钮时,改变样式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="jquery-1.6.4.min.js"></script>
</head>
<style>
#cls{
width: 300px;
height: 300px;
background-color: cadetblue;
}
</style>
<body>
<button id="btn">点击改变内容</button>
<div id="cls">今天天气太好了,有点热</div>
<script>
// 页面的加载事件
$(function(){
// 获取按钮
$("#btn").click(function(){
// 改变样式
$("#cls").css("backgroundColor","chocolate");
$("#cls").css("color","white");
})
})
</script>
</body>
</html
获取时,需要加 #
2).$(".样式选择器名称"):代替document.getElementsByClassName(“样式选择器名称”);
<style>
.cls{
background-color: cadetblue;
}
</style>
<body>
<button id="btn">点击改变内容</button>
<ul>
<li class="cls">郭靖</li>
<li>杨过</li>
<li class="cls">独孤求败</li>
<li>黄蓉</li>
</ul>
<script>
// 页面的加载事件
$(function(){
// 获取按钮
$("#btn").click(function(){
// 改变样式
$(".cls").css("backgroundColor","red");
})
})
</script>
也可以写成 $(“li.cls”).css(“backgroundColor”,“red”);
3).$(“标签类型名”):代替document.getElementsByTagName();
<button id="btn">点击改变内容</button>
<p>js</p>
<p>jquery</p>
<p>vue</p>
<p>bootstrap</p>
<p>ajax</p>
<script>
// 页面的加载事件
$(function(){
// 获取按钮
$("#btn").click(function(){
// 改变样式
$("p").css("backgroundColor","red");
$("p").css("color","white");
$("p").css("fontSize","20px");
})
})
</script>