具有多个选择器的 jQuery .each() - 跳过,然后是 .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< /code> 包含 JS 我想禁用
- jQuery 1.2.3 的 Stuck
谢谢!
I'd like to remove all matching elements, but skip the first instance of each match:
// 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>
Any suggestions?
- Using
jQuery()
rather than$()
because of conflict with 'legacy' code - Using
.empty()
because.a
contains JS I'd like to disable - Stuck with jQuery 1.2.3
Thanks you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下:
我不确定是否可以使用
:gt()
将它们合并到一个选择器中,它可能会更改范围并在第一个.a 之后删除所有它们
。Give this a try:
I'm not sure if combining them into one selector is possible with the
:gt()
, it may change the scope and remove all of them after the first.a
.您的 HTML 似乎不正确。我将其修改为以下内容:
然后这似乎有效:
It looks like your HTML is incorrect. I modified it to the following:
Then this seemed to work: