質問

これらの 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

OK、これが修正されたバージョンです パデル動作する解決策 少し 違う

var lastA = null;

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

他のヒント

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

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

よろしく...

わかった!

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

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

    //do stuff
});​

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

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

これは機能しますか?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top