Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

jquery - How to find next similar sibling moving down in the dom tree

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 provides two alternatives: .nextUntil() and .nextAll()

These can be used as:

nextdt = thisdt.nextUntil("dt").next();
nextdt = thisdt.nextAll("dt").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(); 

Example fiddle: https://jsfiddle.net/0wk1mkeq/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...