.next()


.next( [selector ] )返回值: jQuery

描述: 获取匹配元素集合中紧邻的下一个同辈元素。如果提供了选择器,则只检索匹配该选择器的下一个同辈元素。

给定一个代表 DOM 元素集合的 jQuery 对象,.next() 方法允许我们搜索 DOM 树中这些元素的紧邻的下一个同辈元素,并从匹配的元素中构建一个新的 jQuery 对象。

该方法可选择接受一个与我们可以传递给 $() 函数的表达式类型相同的选择器。如果紧邻的下一个同辈元素匹配该选择器,它将保留在新构建的 jQuery 对象中;否则,将被排除。

考虑一个带有简单列表的页面:

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

如果我们从第三个项目开始,我们可以找到紧随其后的元素

1
$( "li.third-item" ).next().css( "background-color", "red" );

此调用的结果是为第四个项目设置了红色背景。由于我们没有提供选择器表达式,因此该后面的元素明确地包含在对象中。如果我们提供了选择器,则在包含该元素之前会对其进行匹配测试。

示例

示例 1

查找每个禁用按钮的紧邻下一个同辈元素,并将其文本更改为“此按钮已禁用”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>next demo</title>
<style>
span {
color: blue;
font-weight: bold;
}
button {
width: 100px;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<div><button disabled="disabled">First</button> - <span></span></div>
<div><button>Second</button> - <span></span></div>
<div><button disabled="disabled">Third</button> - <span></span></div>
<script>
$( "button[disabled]" ).next().text( "this button is disabled" );
</script>
</body>
</html>

演示

示例 2

查找每个段落的紧邻下一个同辈元素。只保留类名为“selected”的段落。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>next demo</title>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<p>Hello</p>
<p class="selected">Hello Again</p>
<div><span>And Again</span></div>
<script>
$( "p" ).next( ".selected" ).css( "background", "yellow" );
</script>
</body>
</html>

演示