这是我推荐的解决方案:
http://jsfiddle.net/j9RXR/29/
function unqOrMsgTest() {
var rows = $("#binning tbody").children('tr');
var totalRows = rows.length;
var idLookup = {};
var i, rowId, resultClass, checkColumn, rowCount, row;
// loops through all rows, convert to jQuery objects and track the IDs
for (i = 0; i < totalRows; i++)
{
row = $(rows[i]);
rowId = row.children('td[col="check"]').attr("rowid");
rows[i] = row;
idLookup[rowId] = (rowId in idLookup) ? idLookup[rowId] + 1 : 1;
}
// loop through each row and check them for redundancy
for (var i = 0; i < totalRows; i++ )
{
// grab row identifer to check against the id lookup
row = rows[i];
checkColumn = row.children('td[col="check"]');
rowId = checkColumn.attr("rowid");
//this bit of logic picks a class to assign rows
rowCount = idLookup[rowId];
resultClass = rowCount < 2 ? "unique" : "notUnique";
//apply the row class and print the redundancy number into td
checkColumn.text(rowCount);
row.attr("class", resultClass);
};
}
与上述建议使用关联数组(或哈希)来存储 id 和计数的答案类似,我还删除了所有对list.each( function() {...} )
dom 元素到 jQuery 对象的调用并最小化了转换次数。
我删除使用的原因each
是因为每次迭代都会创建一个新的匿名函数,还调用了从 this 到 $(this) 的冗余转换,更不用说堆栈抖动了。只需说一个简单的 for 循环就足够了,而且速度更快。
有关 jQuery 陷阱的更多信息,请查看要避免的 jQuery 陷阱