缓慢的JQuery功能 [英] Slow JQuery function
问题描述
我在JQuery和JS中有这样的功能.我有一个带复选框的div列表,并将它们添加到我的列表中.可以在40个div上正常工作,但有时我有2,000个,并且崩溃了Chrome并在FF上进行了抓取.还是要使它更快?
I have a function like this in JQuery and JS. I have a list of divs with checkboxes and am adding them to my list. This works fine for like 40 divs, but sometimes I have 2,000 and it crashes Chrome and crawls on FF. Anyway to make this faster?
function AddToList()
{
$('div[name="notadded"] input:checked').each(function(index)
{
var html = $(this).parents('div[name="notadded"]').html();
//get rid of the class that is used to gather checkboxes in select/deselect
html = html.replace('listvars', 'addedvars');
var var_id = $(this).attr('value');
var new_html = '<div id="added_' + var_id + '" name="added">' + html + '</div>';
//hide the one we are adding and remove the check
$(this).parents('div[name="notadded"]').hide();
$('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);
//add the vars to the added list
$('.addedList').append(new_html);
step3 = '3b';
});
}
推荐答案
您正在执行2000次DOM操作,不是一个好方法.尝试进行2,000个字符串操作和一个DOM插入.
You're doing 2000 DOM manipulations, not a good way to go. Trying doing 2,000 string manipulations and one DOM insert.
function AddToList()
{
var new_html = "";
$('div[name="notadded"] input:checked').each(function(index)
{
var html = $(this).parents('div[name="notadded"]').html();
//get rid of the class that is used to gather checkboxes in select/deselect
html = html.replace('listvars', 'addedvars');
var var_id = $(this).attr('value');
var new_html += '<div id="added_' + var_id + '" name="added">' + html + '</div>';
//hide the one we are adding and remove the check
$(this).parents('div[name="notadded"]').hide();
$('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);
//add the vars to the added list
step3 = '3b';
});
$('.addedList').append(new_html);
}
此外,根据经验,取消选中2,000个复选框会严重影响性能.我下注将这一行删除:
Also, from experience, unchecking 2,000 checkboxes is seriously performance intensive. I'll wager taking this line out:
$('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);
将改变一切.我建议将这个函数重写为字符串替换,用这种方法会快很多.
Will change everything. I'd recommend rewriting this function as a string replace, it'll be a hell of a lot faster that way.
这篇关于缓慢的JQuery功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!