.next()
.next( [ selector ] ) 返回: jQuery
描述: 取得一個(gè)包含匹配的元素集合中每一個(gè)元素緊鄰的后面同輩元素的元素集合。如果提供一個(gè)選擇器,它檢索下一個(gè)匹配選擇器的兄弟元素。
-
version added: 1.0.next( [ selector ] )
selector選擇器字符串,用于確定到哪個(gè)前輩元素時(shí)停止匹配。
如果提供的jQuery代表了一組DOM元素, .next()方法允許我們找遍元素緊鄰的后面同輩元素所在的DOM樹,構(gòu)建新的匹配元素的jQuery對象。
該方法選擇性地接受同一類型選擇表達(dá),我們可以傳遞給$()函數(shù)。如果緊隨兄弟匹配選擇器,它在新建成的jQuery對象中留下;否則,它被排除在外。
考慮一個(gè)頁面上一個(gè)簡單的列表:
<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>
如果我們從第三個(gè)項(xiàng)目開始,我們可以找到它之后的元素:
$('li.third-item').next().css('background-color', 'red');
調(diào)用后的結(jié)果是項(xiàng)目4變成紅色背景,由于我們沒有提供一個(gè)選擇器表達(dá)式,祖先元素都是返回的jQuery對象的一部分。如果我們有提供一個(gè)選擇的表達(dá)式,只有在這些匹配的項(xiàng)目將包括在內(nèi)。
Examples:
Example: Find the very next sibling of each disabled button and change its text "this button is disabled".
<!DOCTYPE html>
<html>
<head>
<style>
span { color:blue; font-weight:bold; }
button { width:100px; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.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>
Demo:
Example: Find the very next sibling of each paragraph. Keep only the ones with a class "selected".
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.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>