如何找到在dom树中向下移动的下一个相似兄弟 [英] How to find next similar sibling moving down in the dom tree

查看:71
本文介绍了如何找到在dom树中向下移动的下一个相似兄弟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里需要的是放置在dt元素之一上的位置,我想跳到下一个dt元素.我该如何实现?

What I need over here is while positioned on one of the dt elements I want to jump to the next dt element. How can I achieve this?

<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);

推荐答案

jquery中最明显的选项是:.next("dt")并非如此,因为.next()始终仅返回下一个同级项,并应用了过滤器仍仅返回下一个同级,但前提是它与过滤器匹配

What appears to be the obvious option in jquery: .next("dt") is not, because .next() always only returns the very next sibling, applying a filter .next(filter) still only returns the very next sibling, but only if it matches the filter

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

jQuery provides two alternatives: .nextUntil() and .nextAll()

这些可以用作:

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

其中nextUntil获取下一个同级,直到匹配为止(因此您需要另一个next()),nextAll获取所有匹配项(因此您需要first()).

where nextUntil gets the next siblings until the match (so you then need another next()) and nextAll gets all the matching (so you then need first()).

在问题的代码中,进行了以下更新:

In the question's code, this gives the following update:

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

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

这篇关于如何找到在dom树中向下移动的下一个相似兄弟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆