如何使用jQuery将" title"属性转换为鼠标悬停事件?

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

我在"表"" td"元素中有一个" span"元素。 span标签具有标题。

我想获取该span标签的标题并将其拉出,以使其成为" td"元素的" mouseover"提示。

例如:

我想转这个:

<td>
    <a href="#"><span id="test" title="Acres for each province">Acres</span></a>
</td>

变成这个:

<td onmouseover="tip(Acres for each province)">
    <a href="#"><span id="test">Acres</span></a>
</td>

编辑:我不认为你们理解。我正在尝试将onmouseover函数放入" td"标签中。我不打算将其放入" span"标签中。

解决方案

就像是:

$("span#test").mouseover( function () {
   tip($(this).attr("title"));
}

使用jQuery:

$('#test').attr('title')

根据编辑,我们可以检查jQuery的DOM遍历方法:http://docs.jquery.com/Traversing

遵循这些原则(未经测试,我不认为它在语法上是正确的,这里只是一般性的想法)...

$("td").each(function()
{
    $(this).mouseover(function()
    {
        tip($(this).children("span").attr("title"));
    });
});

如果我们不能在td上放置类或者以某种方式选择它,则从选择跨度开始,然后转到跨度的祖父母并添加到鼠标悬停上:

// get each span with id = test
$("span#test").each(function(){
    var $this = $(this);
    // attach to mouseover event of the grandparent (td)
    $this.parent().parent().mouseover( function () {
        tip($this.attr("title"));
    }
);

好的,我也会尝试的:P

$("#yourTable").find("td").over(function()
  { generateTip($(this).find("span:first").attr("title") }
  , function() { removeTip() }
)

这是做什么的:

  • 获取ID为yourTable的表
  • 选择所有的td
  • 插入mouseover和mouseout事件
  • mouseover事件:使用该td中第一个跨度的标题值调用generateTip函数
  • mouseout事件:调用removeTip()(可选)函数。