.next([selector]) 取得**每個**匹配元素**緊鄰的後一個**同輩元素。若提供選擇器,則只有緊鄰元素符合選擇器時才返回。
關鍵特性:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$("span").click(function() {
// 找到每個 <p> 緊鄰的下一個 class="selected" 元素
alert($("p").next(".selected").html());
// 若無參數:$("p").next().html() 取緊鄰的下一個元素(無論類別)
});
});
</script>
</head>
<body>
<p>Hello</p>
<p class="selected">這裡的內容將顯示</p>
<div>
<span>點我測試</span>
</div>
</body>
</html>
點擊「點我測試」彈窗顯示:「這裡的內容將顯示」。
| 方法 | 說明 | 返回 |
|---|---|---|
.next() | 緊鄰的下一個同輩 | jQuery (0或1個元素) |
.nextAll() | 所有後續同輩 | jQuery (多個元素) |
.nextUntil(selector) | 直到符合選擇器前的所有同輩 | jQuery |
.prev() | 緊鄰的上一個同輩 | jQuery |
.siblings() | 所有同輩(前後) | jQuery |
<dl>
<dt>標題 1</dt>
<dd class="content">內容 1</dd>
<dt>標題 2</dt>
<dd class="content">內容 2</dd>
</dl>
<script>
// 點擊 dt 展開/收合對應 dd
$('dt').click(function() {
$(this).next('.content').slideToggle();
});
</script>
此結構中 dd 緊鄰在 dt 之後,.next('.content') 精準命中。
.next() 返回所有後續元素 → 應用 .nextAll()。.html() 會報錯 → 建議先判斷 .length。.parent().next().find(...) 等組合。