【发布时间】:2021-09-28 13:51:46
【问题描述】:
我目前使用此功能根据每个表格单元格的行名(行中最左侧的单元格)和列名(列中最顶部单元格的值)添加工具提示。它按预期工作,但根据 Google Chrome DevTools,它消耗了大量的脚本时间。如何加快速度?
const add_tooltip = function(context) {
context.find("th").each(function() {
$(this).attr("title", $(this).text());
});
context.find("td").each(function() {
$(this).attr("title", $(this).siblings("th").text() + ", " + context.find("thead th").eq($(this).index()).text());
});
};
add_tooltip($("table"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>test</td>
<td>test</td>
</tr>
<tr>
<th>2</th>
<td>test</td>
<td>test</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
可以将
context.find("thead th")缓存到变量中 -
除上述之外,如果您循环遍历
tr然后tds 在该tr 中,您还可以缓存$(this).siblings("th")而无需使用siblings。另外,不仅仅是缓存context.find("thead th"),而是将所有的thead文本缓存到一个数组中 -
作为替代方案,您可能并不需要所有这些工具提示(假设有问题的代码是一个大大缩减的示例)。使用斑马条纹/报纸行(即每行的颜色略有不同),以便用户可以沿着行穿过。
-
另一种选择:在构建 html(后端)时设置工具提示,而不是通过 javascript。
标签: jquery html-table web-performance