![4ff581df5e383017746a022777a7eae3.png](https://img-blog.csdnimg.cn/img_convert/4ff581df5e383017746a022777a7eae3.png)
好好学习,天天向上
本章主要内容是:JQ其他关系查找方法,find() 后代元素、紧邻的兄弟元素方法(单多选)
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 1000px;
height: 80px;
border: 1px solid #333;
margin-top: 10px;
background-color: #fff;
}
.box p,
.box span {
float: left;
width: 80px;
height: 80px;
margin-right: 20px;
background-color: #ccc;
}
.box span {
background-color: pink;
}
</style>
</head>
<body>
<div class="box" id="box1">
<p></p>
<p></p>
<p></p>
<p>
<!-- <span></span> -->
</p>
<span></span>
<span></span>
<span></span>
</div>
<div class="box">
<p></p>
<p></p>
<p></p>
<p></p>
<span></span>
<span></span>
<span></span>
</div>
<div class="box">
<p></p>
<p></p>
<p></p>
<p></p>
<span></span>
<span></span>
<span></span>
</div>
<script src="js/jquery-1.12.4.min.js"></script>
<script>
// 获取元素
var $box1 = $("#box1")
var $box = $(".box")
var $child = $box.children()
</script>
</body>
</html>
1、find() 后代元素
- jQuery 对象可以利用 find() 方法,传递一个参数,参数部分规定的选择器,查找范围是 jQuery 对象的所有后代
- 参数是字符串格式的选择器
// find() 方法查找后代中的 span 元素
$box1.find("span").css({
"width": 50,
"height": 50
})
![699626cb1a0b153aee8187f86f02d510.png](https://img-blog.csdnimg.cn/img_convert/699626cb1a0b153aee8187f86f02d510.png)
2、兄弟元素
紧邻的兄弟元素方法
- next() 下一个兄弟
- prev() 前一个兄弟
$child.click(function () {
// 让自己变红色,让下一个兄弟变粉色
$(this).css("background-color", "red")
.next().css("background-color", "skyblue")
// 让自己变红色,让上一个兄弟变蓝色
$(this).css("background-color", "red")
.prev().css("background-color", "yellow")
})
![5134a4621885fbf07c0c086163931c15.png](https://img-blog.csdnimg.cn/img_convert/5134a4621885fbf07c0c086163931c15.png)
多选方法
- nextAll() 后面所有兄弟
- prevAll() 前面所有兄弟
- 通过传递参数可以进行二次选择,参数是字符串格式的选择器,在前面或后面兄弟中选中 符合选择器规定的部分
$child.click(function () {
// 让自己变红色,让前面所有兄弟变蓝色,让后面所有兄弟变黄色
$(this).css("background-color", "red")
.prevAll().css("background-color", "blue")
$(this).nextAll("p").css("background-color", "yellow")
})
![606eb80e1701c2a4c00b7ed3339c65aa.png](https://img-blog.csdnimg.cn/img_convert/606eb80e1701c2a4c00b7ed3339c65aa.png)
3、parents() 祖先级
- 通过该方法得到的是指定对象的包含 body 在内的所有祖先级元素组成的 jQuery 对象
- 通过传参进行二次选择,参数位置是字符串格式的选择器
$child.click(function () {
// // 让自己变红色,祖先级变天蓝色
$(this).css("background-color", "red")
.parents("div").css("background-color", "skyblue")
})
![ce243ad590c6ef729fc01daef91641a0.png](https://img-blog.csdnimg.cn/img_convert/ce243ad590c6ef729fc01daef91641a0.png)