我想删除所有匹配元素,但是跳过每场比赛的第一个实例:

// 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();

我不确定是否将它们组合到一个选择器中 :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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top