jquery – 如何找到下一个在dom树中向下移动的类似兄弟

前端之家收集整理的这篇文章主要介绍了jquery – 如何找到下一个在dom树中向下移动的类似兄弟前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要的是,当我想要跳转到下一个dt元素时,在其中一个dt元素上定位.我怎样才能做到这一点?
  1. <dl class="accordion">
  2. <dt>Select Category</dt>
  3. <dd></dd>
  4.  
  5. <dt>select product</dt>
  6. <dd></dd>
  7. </dl>
  1. (function($) {
  2. var allPanels = $('.accordion > dd').hide();
  3. $('.accordion > dd:first-of-type').show();
  4. $('.accordion > dt:first-of-type').addClass('accordion-active');
  5.  
  6. jQuery('.accordion > dt').on('click',function() {
  7. $this = $(this);
  8. $target = $this.next();
  9. if (!$this.hasClass('accordion-active')) {
  10. $this.parent().children('dd').slideUp();
  11. jQuery('.accordion > dt').removeClass('accordion-active');
  12. $this.addClass('accordion-active');
  13. $target.addClass('active').slideDown();
  14. }
  15. return false;
  16. });
  17. })(jQuery);

解决方法

似乎是jquery中显而易见的选项:.next(“dt”)不是,因为.next()总是只返回下一个兄弟,应用过滤器.next(过滤器)仍然只返回下一个兄弟,但是只有它与过滤器匹配

jQuery提供了两种选择:.nextUntil().nextAll()

这些可以用作:

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

其中nextUntil获得下一个兄弟,直到匹配(所以你需要另一个next())和nextAll得到所有的匹配(所以你需要first()).

在问题的代码中,这提供了以下更新:

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

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

猜你在找的jQuery相关文章