我有一個包含字符串列表的數百行的html表。我也有一個輸入框,可以在表格中插入新的行。每一行中的第二個TD元素始終是一個div內的字符串,所以在表中的行可能是這樣的:使用jquery通過很多元素搜索時減慢
<tr>
<td><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
</td>
<td class="a_string" style="width:200px;">
<div style="word-wrap:break-word;">hello world</div>
</td>
...
</tr>
我想插入新行基於從一個字符串列表,在此表用戶,如果一個字符串已經在表中,它將被忽略並且不被插入。當用戶字符串列表非常長且表中的行數很長時,我用來檢查重複項的方法效率太低,因此對於此任務來說效率太低:
function check_rows(item) { //called on each item in input list
var tf = false;
$('#mytable tbody').children().each(function (i) {
//loop through each tr
if ($('#mytable tbody').children().eq(i).children().eq(1).hasClass('a_string')) {
//if the row is a string to compare (second td element has the class 'a_string')
if (item == $('#mytable tbody').children().eq(i).children().eq(1).children().eq(0).html()) {
//find the string within the div within second td in row "i" (current indexed row)
//compare the strings and if it is found in the table break out of the loop
tf = true;
return false;
}
}
});
//if the item is not found in any of the rows false will be returned
return tf;
}
該函數做它應該做的事(檢查重複的字符串),它只是太慢了。我試圖插入沒有這個功能的列表,它幾乎是瞬間的,所以問題在這裏。
有關如何改善此功能的任何建議將不勝感激!
$('#mytable tbody')'被調用的次數太多。你有沒有嘗試存儲參考?你能跟蹤數組中的項目列表,而不是從DOM中檢查項目嗎? – nhahtdh 2013-02-16 01:36:41
@nhahtdh是的,我可以,我不認爲這會產生任何效果。我一直不關心jquery的執行速度,因爲直到現在它還沒有實現。將存儲對tbody的引用並將表中的項目數組保存在一起會提高我的性能? – 2013-02-16 01:43:51
有太多的DOM遍歷,這有點更好 - > [** FIDDLE **](http://jsfiddle.net/tsu5c/),但不是很多? – adeneo 2013-02-16 01:46:11