2

一致するすべての要素を削除したいのですが、各一致の最初のインスタンスをスキップします。

// Works as expected: removes all but first instance of .a
jQuery ('.a', '#scope')
    .each ( function (i) { 
        if (i > 0) jQuery (this).empty();
    });

// Expected: removal of all but first instance of .a and .b
// Result: removal of *all* instances .a and .b
jQuery ('.a, .b', '#scope')
    .each ( function (i) { 
        if (i > 1) jQuery (this).empty();
    });

<div id="scope">

    <!-- Want to keep the first instance of .a and .b -->

    <div class="a">[bla]</div>
    <div class="b">[bla]</div>

    <!-- Want to remove all the others -->

    <div class="a">[bla]</div>
    <div class="b">[bla]</div>

    <div class="a">[bla]</div>
    <div class="b">[bla]</div>
    ...
</div>

助言がありますか?

  • 「レガシー」コードとの競合のためでjQuery()はなく使用$()
  • 無効にしたいJSが含まれている.empty()ため使用.a
  • jQuery 1.2.3で立ち往生

ありがとうございます!

4

2 に答える 2

3

これを試してください:

$('.a:gt(0), .b:gt(0)').remove();

を使用してそれらを 1 つのセレクターに結合できるかどうかはわかりません:gt()。スコープが変更され、最初の の後にすべてが削除される可能性があります.a

于 2010-03-19T21:56:16.157 に答える
1

HTML が間違っているようです。次のように変更しました。

<div id="scope">

    <!-- Want to keep the first instance of .a and .b -->

    <div class="a">[bla]</div>
    <div class="b">[bla]</div>

    <!-- Want to remove all the others -->

    <div class="a">[bla]</div>
    <div class="b">[bla]</div>

    <div class="a">[bla]</div>
    <div class="b">[bla]</div>
    ...
</div>

次に、これはうまくいくように見えました:

jQuery('div#scope div.a').not(':first').empty();
jQuery('div#scope div.b').not(':first').empty();
于 2010-03-19T22:08:32.673 に答える