使用Jquery移除包括($this)在内的所有下一个元素

5

这里有一个简单的问题:

是否有比jquery更好的替代方法来删除下一个所有元素,包括($this)?

到目前为止,以下代码对我有效:$(this).nextAll().remove();$(this).remove();


2
如果你所说的更好的替代方法是令人讨厌的链接,那么 $(this).nextAll().remove().end().remove(); - Esailija
3个回答

10

如果您想要链接您的调用,那么有几个选项可供选择,但这并不会对性能产生太大影响:

$(this).nextAll().remove().end().remove();

$(this).nextAll().add(this).remove();

$(this).nextAll().andSelf().remove();

.end():

结束当前链中最近的筛选操作,并将匹配的元素集返回到其先前的状态。

http://api.jquery.com/end

.add():

将元素添加到匹配元素集。

http://api.jquery.com/add

.andSelf():

将堆栈上前一次的元素集添加到当前集合中。

http://api.jquery.com/andself


$(this).nextAll().add(this).remove(); 更简洁。 - Joseph Marikle
你说得对,我在那里不必要地使用了jQuery,谢谢。 - Jasper
我们应该收集更多的方法来以链式方式完成这个任务,3个还不够:D - Esailija

3
$(this).nextAll().andSelf().remove();

2
你可以使用.nextAll()方法,然后添加this,最后在组合集合上调用.remove()方法:
$(this).nextAll().add(this).remove();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接