2016-07-25 58 views
0

我在這裏需要的是雖然位於其中一個dt元素我想跳轉到下一個dt元素。我怎樣才能做到這一點?如何找到下一個類似的兄弟姐妹在dom樹下移動

<dl class="accordion"> 
    <dt>Select Category</dt> 
    <dd></dd> 

    <dt>select product</dt> 
    <dd></dd> 
</dl> 
(function($) { 
    var allPanels = $('.accordion > dd').hide(); 
    $('.accordion > dd:first-of-type').show(); 
    $('.accordion > dt:first-of-type').addClass('accordion-active'); 

    jQuery('.accordion > dt').on('click', function() { 
     $this = $(this); 
     $target = $this.next(); 
     if (!$this.hasClass('accordion-active')) { 
      $this.parent().children('dd').slideUp(); 
      jQuery('.accordion > dt').removeClass('accordion-active'); 
      $this.addClass('accordion-active'); 
      $target.addClass('active').slideDown(); 
     }  
     return false; 
    }); 
})(jQuery); 
+0

是什麼thisdt? –

+0

它不工作... $ this.next(「dt」)指向相同的元素,這是點擊某種方式...我想在dom –

+0

'$ target = $ this.nextAll('dt')的下一個dt元素.EQ(0);'? –

回答

4

什麼似乎是jQuery中的明顯的選擇:.next("dt")不是,因爲.next()總是隻返回第二天的兄弟姐妹,應用過濾器.next(filter)仍只返回第二天的兄弟姐妹,但只有當它匹配濾波器

jQuery提供兩種選擇:.nextUntil().nextAll()

這些可以用作:

nextdt = thisdt.nextUntil("dt").next(); 
nextdt = thisdt.nextAll("dt").first(); 

其中nextUntil獲取下一個兄弟直到匹配(所以你需要另一個next())並且nextAll獲得所有匹配(所以你需要first())。

在問題的代碼,這給了以下更新:

jQuery('.accordion > dt').on('click', function() { 
    $this = $(this); 
    $target = $this.nextAll("dt").first(); 

例小提琴:https://jsfiddle.net/0wk1mkeq/

+0

+1你說得對,那並不明顯。如果我不得不猜測你的解釋,我的猜測是'next('filter')'返回匹配過濾器的下一個元素,而這將是錯誤的。一個有用的說明。 – BobRodes