2010-03-19 92 views
2

我想刪除所有匹配的元素,但跳過每場比賽的第一個實例: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

謝謝您!

回答

3

試試這個:

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

我不知道,如果它們合併成一個選擇是可能的:gt(),它可能會改變範圍,它們全部刪除第一.a後。

+0

它_is_可以使用':GT()'具有組合的選擇器: '的jQuery(」。 a:gt(0),.b:gt(0)')。empty()'效果很好。 你能提出爲什麼我的方法不起作用嗎? 謝謝! – joe 2010-03-19 22:33:59

+0

哦,不,你是對的我試過了,你的工作也很好。 **編輯我的答案**。 – 2010-03-19 23:58:14

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(); 
+0

HTML錯字僅在我的簡單示例中。 感謝您的建議! – joe 2010-03-19 22:36:10