2011-07-27 76 views
3

我有以下代碼:jQuery的下一個()沒有得到下一個元素

<h1><a href="#" class="link">Click here</a></h1> 
<div class="acitem"></div> 
<div class="acitem2"></div> 

<script> 
    $(document).ready(function() { 
     $('a.link').click(function() { 
      var element = $(this).next(); 

      alert(element.attr('class')); 
     }); 

    }); 
</script> 

當我有一個H1標籤內包裹的「點擊這裏」鏈接時,警報調用返回「不確定」,但如果我從鏈接中刪除H1標籤,然後警報調用正確返回'acitem'。隨着H1標籤到位,我也試過:

$(this).nextUntil('.acitem') 

但是,這仍然返回'未定義'。

對於next()函數如何在JQuery中工作,我有點困惑。任何人都知道爲什麼只有從鏈接中刪除H1標籤,下一個功能才能正常工作?有什麼我做錯了嗎?

謝謝!

回答

11

next()作品兄弟姐妹,在你的結構,<a>是獨生子女<h1>了,所以叫next()在技術上沒有返回值作爲<a><h1>唯一的兒子。 Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

http://api.jquery.com/next/

nextUntil()得到一組指定的參數從選擇器可啓動,但不包括選擇的元素,引用文檔:因此,爲什麼,如果你刪除<h1>

引述文檔它的工作原理:Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.

http://api.jquery.com/nextUntil/

關於您的查詢,您可致電.parent(),然後致電next()確保您獲得其父母的兄弟姐妹(即他的叔叔)

<script> 
    $(document).ready(function() { 
     $('a.link').click(function() { 
      var element = $(this).parent().next(); 

      alert(element.attr('class')); 
     }); 

    }); 
</script> 
+0

+1很好的答案和完整的解決方案。 –

+1

使用叔叔+1 – ansiart