You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让表格中所有id为tooltipexcess的TD单元格hover时显示tooltip?

解决表格动态行中Tooltip只对第一行生效的问题

问题根源

核心问题是HTML中id属性必须唯一,你给多个<td>都用了id="tooltipexcess",jQuery的$("#tooltipexcess")只会匹配页面中第一个带这个id的元素,所以后面行的单元格完全没触发事件。你后来尝试的代码逻辑混乱,自然也不起作用。

修正步骤

  1. 将重复id改为class:把所有<td>的id="tooltipexcess"替换成class="tooltipexcess",class允许重复使用。
  2. 修正jQuery选择器:用类选择器$(".tooltipexcess")选中所有目标单元格。
  3. 绑定事件(支持动态行):如果表格是动态生成的(后续会新增行),建议用事件委托绑定到父元素(比如<tbody>),确保新添加的行也能触发tooltip。

完整修正代码

<table class="table table-borderless table-sm table-limit-excess rounded mt-2">
    <tbody>
        <tr class="bg-primary text-white">
            <th class="pl-2">Key</th>
            <th class="pr-2">Data</th>
            <th class="pr-2">Condition</th>
        </tr>
        <tr>
            <td>12</td>
            <td class="tooltipexcess" title="123456789012345,  A123456789012345">123456789012345,  A123456789012345</td>
            <td>Equal To</td>
        </tr>
        <tr>
            <td>92</td>
            <td class="tooltipexcess">322312323</td>
            <td>Contains</td>
        </tr>
        <tr>
            <td>230</td>
            <td class="tooltipexcess">123233,  333,  3312213,  2132321,  3fsdff</td>
            <td>Equal To</td>
        </tr>
    </tbody>
</table>

<script>
    // 普通写法(仅对现有行生效)
    $(".tooltipexcess").on("mouseover", function () {
        $(this).attr("title", $(this).text());
    });

    // 事件委托写法(支持动态新增的行)
    // $("tbody").on("mouseover", ".tooltipexcess", function () {
    //     $(this).attr("title", $(this).text());
    // });
</script>

补充说明

  • 如果你的表格是通过JS动态添加行的,就用注释里的事件委托写法,把事件绑定到不会被替换的父元素(比如<tbody>)上,这样新添加的.tooltipexcess单元格也能触发事件。
  • 浏览器原生会识别title属性并显示tooltip,不需要额外插件,只要正确设置title值即可。

内容的提问来源于stack exchange,提问作者Bill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 08:00:30