【问题标题】:jQuery Speed up adding tooltips to table cells according to row and column namejQuery 根据行和列名称加快向表格单元格添加工具提示
【发布时间】: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


【解决方案1】:

这是我在收集大家的反馈后想出的新功能。我已经对其进行了测试,它似乎并不比在使用$.append() 构造表时包含title 属性慢多少(这使得代码非常笨拙)。

const add_tooltip = function (context) {
    let row_names = [], column_names = [];

    context.find("th").each(function () {
        $(this).attr("title", $(this).text());

        if ($(this).parents("thead").length)
            column_names.push($(this).text());
        else
            row_names.push($(this).text());
    });

    context.find("tbody, tfoot").find("tr").each(function (i) {
        $(this).find("td").each(function (j) {
            $(this).attr("title", `${row_names[i]}, ${column_names[j + 1]}`);
        });
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多