0

假设我有一个如下列表:

<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

4 回答 4

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/

于 2013-07-15T12:49:20.980 回答
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();  
}  
于 2013-07-15T12:30:41.123 回答
2

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

于 2013-07-15T12:35:58.080 回答
0

听起来您正在寻找的是.filter()函数。
有了这个,您将能够选择几乎任何您想要的东西。
给它看看:)

假设您只想要li值为 1 的 :

$(document).ready(function() {
    $('#list li').filter(function (index) {
        return $(this).value == "1";
    })
});
于 2013-07-15T12:35:34.703 回答