13

これらの 4 つの HTML スニペットがあります。

  • 兄弟:

    <div class="a">...</div>
    <div class="b">...</div>        <!--selected-->
    <div class="b">...</div>        <!--not selected-->
    
  • ラップされた 1:

    <div class="a">...</div>
    <div>
        <div class="b">...</div>    <!--selected-->
    </div>
    <div class="b">...</div>        <!--not selected-->
    
  • ラップされた 2:

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

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

jQuery を使用して、ネストに関係なく、.b特定の要素の次の要素を選択するにはどうすればよいですか?.a

私はこのようなものが欲しい:

$('.a').each(function() {
    var nearestB = $(this)./*Something epically wonderful here*/;

    //do other stuff here
});
4

5 に答える 5

3

これを試して、あなたのケースに合っているかどうかを確認できますか?

    $(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;
            }
        });
    });

よろしく...

于 2010-06-29T13:56:57.047 に答える
3

とった!

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

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

    //do stuff
});​
于 2010-06-29T14:11:00.343 に答える
2

どちらを選択するかをどのように決定してい.aますか?.b永遠はあり.aますか?それぞれをループしていますか?のインデックスを使用して.a、対応する を選択するだけ.bです。

$(".a").each(function(){
    var index = $(".a").index(this);
    var theB = $(".b").get(index);
});
于 2010-06-29T13:35:14.383 に答える
1

OK、これはPadelのソリューションの修正版で、動作が少し異なります

var lastA = null;

$('.a, .b').each(function() {
    if($(this).hasClass('a'))
    {
        lastA = $(this);
    }
    else if(lastA)
    {
        doStuff(lastA,this); //doStuff(a,b)
        lastA = null;
    }
});
于 2010-06-29T14:47:10.743 に答える
0
$("div.a").nextAll("div.b")

これは機能しますか?

于 2010-06-29T13:33:33.513 に答える