如何使用jquery将工具提示添加到" td"?

时间:2020-03-06 15:03:40  来源:igfitidea点击:

我需要使用jquery在我的表内部的" td"元素中添加工具提示/ alt。

有人可以帮我吗?

我试过了:

var tTip ="Hello world";
$(this).attr("onmouseover", tip(tTip));

在此已验证我将" td"用作" this"。

**编辑:**我能够通过使用" alert"命令捕获" td"元素,并且它可以正常工作。因此出于某种原因,"提示"功能无法正常工作。有人知道为什么会这样吗?

解决方案

$(this).mouseover(function() {
    tip(tTip);
});

更好的方法可能是将title属性放入HTML中。这样,如果有人关闭了javascript,他们仍然会获得工具提示(尽管不如jQuery那样美观/灵活)。

<table id="myTable">
    <tbody>
        <tr>
            <td title="Tip 1">Cell 1</td>
            <td title="Tip 2">Cell 2</td>
        </tr>
    </tbody>
</table>

然后使用以下代码:

$('#myTable td[title]')
    .hover(function() {
        showTooltip($(this));
    }, function() {
        hideTooltip();
    })
;

function showTooltip($el) {
    // insert code here to position your tooltip element (which i'll call $tip)
    $tip.html($el.attr('title'));
}
function hideTooltip() {
    $tip.hide();
}

var tTip ="Hello world";
$(this).mouseover( function() { tip(tTip); });

我们可能想看看http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/

如果我们确实确实想将这些工具提示放到表格单元格上,而不是放在表格标题上(在它们更有意义的地方),请考虑将其放在表格单元格内更有意义的内容中。

td:nth-​​child(5)列

$('#grdList tr td:nth-child(5)').each(function(i) {
    if (i > 0) { //skip header
        var sContent = $(this).text();
        $(this).attr("title", $(this).html());
        if (sContent.length > 20) {
            $(this).text(sContent.substring(0,20) + '...');
        }
    }
});

$('#grdList tr td:nth-child(5)').each(function(i) {
    if (i > 0) { //skip header
        var sContent = $(this).text();
        $(this).attr("title", $(this).html());
        if (sContent.length > 20) {
            $(this).text(sContent.substring(0,20) + '...');
        }
    }
});

grdList表ID

td:nth-​​child(5)第5列