标记:
<div id="status">
<div style="display: block;">Status OK - 16:57:09.</div>
<div style="display: block;">Status OK - 16:57:09.</div>
<div style="display: block;">Status OK - 16:57:05.</div>
<div style="display: block;">Status OK - 16:57:05.</div>
<div style="display: block;">Status OK - 16:57:03.</div>
<div>No status yet.</div>
</div>
使用 AJAX,我将一个新的 Div 添加到状态 div。我只希望五个 div 一直在里面。意思是在第六个 ajax 类之后,最后一个 div 应该被删除。
这是我的 jQuery 代码:
<script type="text/javascript">
function Update() {
PurgeOldStatuses();
$("#status").children().first().hide().fadeIn();
}
function PurgeOldStatuses() {
// From the status div, find all divs with index after 5, and remove them.
$("#status").$("div:gt(5)").remove();
}
</script>
我在评论中写道,我认为是怎么回事,也许我错了。
目前没有元素被删除。有什么建议吗?
最佳答案
为了获得更好的性能,请避免像 :gt()
这样的专有选择器,并且只使用有效的 CSS 选择器。
这应该很快:
$("#status").find("div").slice(5).remove();
或者这个:
$("#status div").slice(5).remove();
来自 gt-selector
[docs] 的文档:
Because
:gt()
is a jQuery extension and not part of the CSS specification, queries using:gt()
cannot take advantage of the performance boost provided by the native DOMquerySelectorAll()
method. For better performance in modern browsers, use$("your-pure-css-selector").slice(index)
instead.
请注意,文档建议使用 slice()
[docs]方法,它从您提供的从零开始的索引开始获取集合中的所有元素。
关于javascript - 在索引 N 之后使用 jQuery 删除 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7197224/