2012-07-19 63 views
0

我有一个这样的功能在JQuery和JS。我有一个带有复选框的div列表,并将它们添加到我的列表中。这适用于40个div,但有时我有2000个,它会崩溃Chrome并在FF上爬行。无论如何,让这个更快?慢JQuery函数

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'; 
    }); 
} 
+1

听起来像问题是与你的HTML,而不是你的JavaScript。为什么你需要2000个div?必须有许多方法来优化。 – Blazemonger 2012-07-19 19:58:46

+1

你也有名称属性的div? – Chandu 2012-07-19 19:59:08

+0

如果您想做出如此大的替换,请尝试一次完成:构建一个大的html(而不是2000个),并用一个附加内容替换整个集合。 – 2012-07-19 20:00:43

回答

2

您正在做2000个DOM操作,不是一个好的方法。尝试做2000个字符串操作和一个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); 
} 

另外,根据经验,取消选中2000复选框会严重影响性能。我会打这条线:

$('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false); 

会改变一切。我建议重写这个函数作为一个字符串替换,这将是一个快很多的方式。

+0

是的,我会这么做,2000年的操纵绝对是一个不好的方法去 – cdub 2012-07-19 20:06:57