2012-07-19 61 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