jquery .remove performance

jquery .remove performance

本文关键字:performance remove jquery      更新时间:2023-09-26

我正在尝试删除多个div中Ul下的带conditon的li。

<div>
    <ul>
        <li class="sel">.....</li>
        <li class="sel">.....</li>
         ............
        <li>.....</li>
        <li>.....</li>
         ...........
         <!-- I have some 600 li's -->
    </ul>
</div>

我和class='sel'有200里。现在我需要去掉剩下的400里。

我试图通过两种方式删除,比如

$("ul", this).each(function(){
    $("li", this).each(function(){
        $(this).remove();
        //Also tried with -- $(this).empty().remove();
    });
});

其他方式,如

$("ul", this).each(function(){
    $("li[class!=sel]", this).remove(); // Also tried with 'not'
});

现在的问题是,当我试图在IE中执行这些方法时,会出现脚本过载错误。

请帮我找出其他方法来去除不想要的李。

注意:我不想让不想要的李隐藏()状态。

提前感谢。。。

如果您使用的是属性不相等选择器,则不需要用.each()包装它-只需如下调用即可:

$('li[class!="sel"]').remove();

选择器('li[class!="sel"]')获取所有没有类sel<li>元素,然后在整个元素集上调用remove()方法。

演示

编辑

如果您只想以包含<li class="sel"></li>元素的<ul>为目标,您可以设置如下上下文:

// Find the first <li> with class="sel" and get it's parent <ul>
var $ul = $('li.sel:first').parent('ul');
// Use $ul as the context for the removal of the <li> elements
$('li[class!="sel"]', $ul).remove();

值得一提的是,就在几周前,我遇到了一个类似的问题,只是在IE8中,甚至对id选择的单个项目调用.remove()。只有当元素包含大量内容时,问题才会发生。

我所做的是在调用.remove()之前调用.html('')来清除元素。这大大缩短了时间(亚秒)。

我的情况显然不同(一个元素对多个元素,由id和上下文选择器选择,不确定li内容是什么,等等),但这可能值得一试。

$("ul", this).each(function(){
    $("li[class!=sel]", this).html('').remove();
});

尝试分离ul,移除li,然后重新连接ul。

$("ul", this).detach().find("li").not(".sel").remove().end().end().appendTo(this);

这样可以防止浏览器重新绘制,直到所有需要删除的li都被删除为止。