我在JQuery和JS中有这样的函数。我有一个带复选框的div列表,并将它们添加到我的列表中。这适用于40个div,但有时我有2000个,它崩溃Chrome并在FF上爬行。无论如何要加快速度?
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';
});
}
答案 0 :(得分:2)
你正在做2000个DOM操作,不是一个好方法。尝试进行2,000个字符串操作和一个DOM插入。
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个复选框会严重影响性能。我打算把这条线打掉:
$('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);
会改变一切。我建议将此函数重写为字符串替换,这将是一个快得多的地狱。