javascript - 在索引 N 之后使用 jQuery 删除 div

标签 javascript jquery html

标记:

<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 DOM querySelectorAll() 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/

相关文章:

javascript - 输入文件的点击事件第二次不起作用

javascript - 是否可以将渐进式网络应用程序链接到 toast

javascript - 从另一个域获取数据(json格式),无需jsonp

javascript - css 打印查询在 Firefox 中不起作用

html - Firefox 中不显示背景图像

javascript - IE9中如何替换iframe

javascript - 页面刷新后保持复选框被选中

javascript - 在 jQuery 中识别 $(this)

javascript - 专注于表格单元格/列

html - chrome 无法显示特殊字符 é,尽管它在文本编辑器中正确显示