开发者

Is there a jQuery selector to accomplish this task?

开发者 https://www.devze.com 2023-01-05 14:53 出处:网络
I have these 4 HTML snippets: Siblings: <div class=\"a\">...</div> <div class=\"b\">...</div><!--selected-->

I have these 4 HTML snippets:

  • Siblings:

    <div class="a">...</div>
    <div class="b">...</div>        <!--selected-->
    <div class="b">...</div>        <!--not selected-->
    
  • Wrapped 1:

    <div class="a">...</div>
    <div>
        <div class="b">...</div>    <!--selected-->
    </div>
    <div class="b">...</div>        <!--not selected-->
    
  • Wrapped 2:

    <div>
        <div class="a">...</div>
    </div>
    <div>
        <div class="b">...</div>    <!--selected-->
    </div>
    <div class="b">...</div>        <!--not selected-->
    
  • Separated:

    <div class="a">...</div>
    <div>...</div>
    <div class="b">...</div>        <!--selected-->
    <div>...</div>
    <div class="b">...</div>        <!--not selected-->
    <div>...</div>
    <div class="b">...</div>        <!--not selected-->
    

How can I, with jQuery, select the next .b element for any given .a element, regardless of nesting?

I want something like this:

$开发者_StackOverflow社区('.a').each(function() {
    var nearestB = $(this)./*Something epically wonderful here*/;

    //do other stuff here
});


Can you try this to see if it suits your case?

    $(document).ready(function () {
        var isA = false;

        $('div.a, div.b').each(function () {
            if ($(this).attr('class') == "a")
                isA = true;
            if ($(this).attr('class') == "b" && isA) {
                $(this).css("background", "yellow");
                isA = false;
            }
        });
    });

Regards...


Got it!

var both = $('.a, .b');

$('.a').each(function() {
    var nearestB = both.slice(both.index(this))
                       .filter('.b')
                       .first();

    //do stuff
});​


How are you deciding which .a to select? Is there a .b for ever .a? Are you looping over each? You could use the index of the .a and simply select the corresponding .b.

$(".a").each(function(){
    var index = $(".a").index(this);
    var theB = $(".b").get(index);
});


Ok, here's a modified version of Padel's solution, that behaves slightly differently

var lastA = null;

$('.a, .b').each(function() {
    if($(this).hasClass('a'))
    {
        lastA = $(this);
    }
    else if(lastA)
    {
        doStuff(lastA,this); //doStuff(a,b)
        lastA = null;
    }
});


$("div.a").nextAll("div.b")

Does this work?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号