基础选择器
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
<script>
$(function(){
$("p.a")[1].style.color="yellow"
})
</script>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p class="a">sdasdasd</p>
<p class="a">123456</p>
<p class="b">4</p>
<p>5</p>
<p>6</p>
</body>
</html>
当然jQuery有自己设定样式的方法:
$().css("属性","属性值")
效果:
层级选择器
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
<script>
$(function(){
$("p").css("backgroundColor","aqua")
$("p.a")[1].style.color="yellow"
})
</script>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p class="a">sdasdasd</p>
<p class="a">123456</p>
<p class="b">4</p>
<p>5</p>
<p>6</p>
</body>
</html>
效果:
筛选选择器
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
<style>
div {
width: 200px;
height: 200px;
background-color: aqua;
}
</style>
<script>
$(function () {
$("div:eq(1)").css("backgroundColor","red")
});
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
效果:
parent()返回的是最近一级的。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
<style>
div{
width: 200px;
height: 200px;
}
</style>
<script>
$(function () {
$("div:eq(1)").css("backgroundColor","red")
$("div:eq(1)").siblings().css("backgroundColor","yellow")
});
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
效果:
注意以下区别:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
<style>
div{
width: 200px;
height: 200px;
}
</style>
<script>
$(function () {
var index1=2;
var index2=3;
$("div:eq(1)").css("backgroundColor","red")
$("div:eq("+index1+")").css("backgroundColor","aqua");
$("div").eq(index2).css("backgroundColor","yellow")
});
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
效果: