如何使用jQuery统计匹配指定data属性的td元素及对应行数
解决方案
你可以通过单次遍历DOM完成统计,相比两次遍历(先去重再统计)性能更好,同时完全适配任意data-engine属性值的通用统计需求,实现逻辑如下:
核心实现代码
$(document).ready(function () { $('#table_id').DataTable(); // 用对象存储统计结果,键为data-engine值,值为对应出现次数 const engineCount = {}; $('#table_id').find('td[data-engine]').each(function () { const engineVal = $(this).data('engine'); // 已存在则计数+1,不存在则初始化为1 engineCount[engineVal] = engineCount[engineVal] ? engineCount[engineVal] + 1 : 1; }); // 遍历统计结果生成下拉选项 Object.entries(engineCount).forEach(([engine, count]) => { $('.snds').append(`<option value="${engine}">${engine} : ${count}</option>`); }); });
注:这里用jQuery内置的
data('engine')方法读取自定义属性,比直接调用attr更符合jQuery的API规范,也会自动做类型转换(如果属性值是数字、布尔值等类型时适配性更好)。
你原来的实现逻辑是可以正常运行的,优化后版本的优势:
- 仅做1次DOM遍历,DOM操作更少,表格数据量大时性能差异更明显
- 不需要额外维护去重数组,用对象天然实现键的唯一性,逻辑更简洁
- 代码量更少,可维护性更高
如果需要单独获取某个值的统计数,直接读取engineCount['ami']就能得到对应计数,不需要再重新查询DOM。
补充:统计匹配行数(而非td个数)
如果你的表格中可能存在同一行多个td带data-engine属性,需要统计的是包含对应data-engine值的总行数,可按如下逻辑调整:
$(document).ready(function () { $('#table_id').DataTable(); const engineRowCount = {}; // 先遍历行,再判断每行是否有带对应属性的td $('#table_id tbody tr').each(function () { const $tr = $(this); const engineVal = $tr.find('td[data-engine]').first().data('engine'); if (engineVal) { engineRowCount[engineVal] = engineRowCount[engineVal] ? engineRowCount[engineVal] + 1 : 1; } }); Object.entries(engineRowCount).forEach(([engine, count]) => { $('.snds').append(`<option value="${engine}">${engine} : ${count}</option>`); }); });
内容的提问来源于stack exchange,提问作者Smaller
相关产品推荐
相关产品推荐

