jquery .each()複数のセレクターを備えた-skip、then.empty()elements
-
21-09-2019 - |
質問
一致するすべての要素を削除したいのですが、各マッチの最初のインスタンスをスキップします。
// 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()
それよりも$()
「レガシー」コードとの競合のため - 使用
.empty()
なぜなら.a
私が無効にしたいJSが含まれています - jQuery 1.2.3で立ち往生しています
ありがとうございます!
解決
これを試してみてください:
$('.a:gt(0), .b:gt(0)').remove();
それらを1つのセレクターに結合することが可能かどうかはわかりません :gt()
, 、それはスコープを変更し、最初のものの後にそれらすべてを削除するかもしれません .a
.
他のヒント
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();
所属していません StackOverflow