在 DOM 裡往後找兄弟元素,next() 與 nextAll() 是最直接的兩個方法。但它們有一個常被誤解的地方,用範例來看最清楚。
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//$("div").click(function(){ alert($(this).next().text()); });
//$("div").click(function(){ alert($(this).nextAll().text()); });
$("div").click(function(){ alert($(this).nextAll("div").text()); });
});
</script>
<style type="text/css">
div{width:300px;height:30px;background:green;margin-top:10px;}
</style>
</head>
<body>
<div id="uu">您好,<font color="blue">美女</font></div>
<div>hello,world</div>
<div>美女,親一下</div>
<p>我是p標簽</p>
<div><span>我很帥,有圖有真相</span></div>
<p>我也是p標簽</p>
</body>
</html>
next() 取得的是「緊接在自己後面的那一個同層元素」。這裡最容易誤會的是:所謂同層(sibling)指的是同一個父元素下的兄弟關係,而不是標籤名稱相同。以範例來說,<div>美女,親一下</div> 之後緊鄰的元素其實是 <p>,所以 next() 取到的是那個 p。
寫成 next("div") 時,jQuery 只會看「緊鄰的那一個」是否符合條件。如果下一個兄弟不是 div,結果就是空集合,它不會繼續往後找。這一點和 nextAll("div") 完全不同,實務上很容易混淆。
nextAll() 會取得目前元素之後的所有同層元素,同樣可以帶選擇器參數,例如 nextAll("p") 或 nextAll("div")。
把事件改成下面這行:
$("div").click(function(){ alert($(this).nextAll("div").html()); });
你可能會預期它把所有後續 div 的內容都拼起來顯示,但實際只得到「下一個」div 的 HTML。原因在於 .html() 這類取內容的方法只作用於集合中的第一個元素,而不是全部。若要取得每一個元素的內容,必須先遍歷:
$("div").click(function(){
$(this).nextAll("div").each(function(){
alert($(this).html());
});
});
這也是 jQuery 一個一致的設計慣例:讀取類方法回傳第一個元素的結果,設定類方法才作用於整個集合。理解這點,很多「怎麼只抓到一個」的疑惑就自動解開了。