.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" );

這個呼叫的結果會在第 4 個項目後面加上紅色背景。由於我們沒有提供選擇器表達式,因此這個後面的元素會明確包含在物件中。如果我們有提供一個,這個元素會在包含在內之前先進行比對測試。

範例

找到每個已停用按鈕的緊鄰同層元素,並將其文字變更為「這個按鈕已停用」。

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.jquery.com/jquery-3.7.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>

示範

找到每個段落的緊鄰同層元素。只保留那些有「選取」類別的元素。

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.jquery.com/jquery-3.7.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>

示範