我想刪除所有匹配的元素,但跳過每場比賽的第一個實例:jQuery的。每()有多個選擇 - 跳過,然後.empty()元素
// 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
謝謝您!
它_is_可以使用':GT()'具有組合的選擇器: '的jQuery(」。 a:gt(0),.b:gt(0)')。empty()'效果很好。 你能提出爲什麼我的方法不起作用嗎? 謝謝! – joe 2010-03-19 22:33:59
哦,不,你是對的我試過了,你的工作也很好。 **編輯我的答案**。 – 2010-03-19 23:58:14