“准备”要删除的元素

时间:2013-07-15 12:28:36

标签: jquery

假设我有一个如下列表:

<ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

我希望使用jQuery删除一些简单的li元素:

$('#list li').each(function() {
    if(some condition is true)
        $(this).remove();
});
然而,这会导致对DOM的多次操作。为了提高性能,我只想操作DOM一次。

因此,我必须以某种方式“标记”或记住我要删除哪个li,而不是为所有这些li调用jQuerys“remove()”方法一次。

最好的办法是什么?

请在此处查看jsFiddle: http://jsfiddle.net/RfrHM/

4 个答案:

答案 0 :(得分:3)

你可以克隆列表并在内存中操作它(我认为jQuery使用片段),然后用操作的列表替换整个列表:

var $list = $('#list').clone(true);
$list.children().each(function() {
    if ( condition ) {
        $(this).remove();
    }
});
$('#list').replaceWith($list); // the one DOM manip

我不确定这会提高性能,但只需要一个DOM操作,如果这就是你所追求的。

演示:http://jsfiddle.net/3y5NL/

答案 1 :(得分:2)

$('#list li').each(function() {
    if(some condition is true)
        $(this).addClass('toberemoved');
});

稍后在您的代码中:

$('li.toberemoved').remove();

JSFIDDLE

为了更好的性能使用:

var toberemoved = [];

// Not using each speeds up performance (chaining won't work though)
for (var i = 0, $('#list li').length; i < len; i++) {
    if(some condition is true)
        toberemoved.push($('#list li')[i]);
}


// code to remove
var l = toberemoved.length;  
for (var i=0;i<l; i++) {  
    array[i].remove();  
}  

答案 2 :(得分:2)

请参阅document.createDocumentFragment()$.fn.detach() http://learn.jquery.com/performance/detach-elements-before-work-with-them/

答案 3 :(得分:0)

听起来你正在寻找的是.filter()功能。
有了这个,你就可以选择你想要的任何东西。
看看:)

假设您只希望li的值为1:

$(document).ready(function() {
    $('#list li').filter(function (index) {
        return $(this).value == "1";
    })
});
相关问题