3

我为我的链接编写了这个快速工具提示功能:

$(function() {
  $('a').hover(function(e) {
    var title = $(this).attr('title');
    $('<div id="tooltip">' + title + '</div>').css({"top" : e.pageY + 12, "left" : e.pageX + 12}).appendTo('body');
  }, function() {
    $('#tooltip').remove();
  });

  $('a').mousemove(function(e){ 
    $('#tooltip').css({"top" : e.pageY + 12, "left" : e.pageX + 12});
  })
});

我想删除原来的标题,因为两者都是愚蠢的。我知道我应该这样做:

$('a').hover(function() {
  $(this).attr('title', '');
});

问题是我无法将其添加回来。我试过:

$(this).attr('title', title) //from my title variable

但它失败了。建议?

4

2 回答 2

6

存储在title变量中的值是该函数的本地值,并且在函数完成执行后会丢失。

一种解决方案是将先前的标题存储在元素的data().

var $th = $(this);

$th.data( 'prevTitle', $th.attr('title') );

然后在需要时访问它(大概在下一个悬停函数中)。

var $th = $(this);

$th.attr('title', $th.data( 'prevTitle' ));

您可以将变量声明带到两个函数之外。

var title;

$('a').hover(function(e){
     title = $(this).attr('title');
     $('<div id="tooltip">' + title + '</div>').css({"top" : e.pageY + 12, "left" : e.pageX + 12}).appendTo('body');
}, function(){
    $th.attr('title', title);
    $('#tooltip').remove();
});

...但我认为使用data()会更安全。

于 2010-07-03T11:23:23.053 回答
2

您的 title 变量仅存在于第一个处理程序的范围内。您必须将值存储在第二个处理程序可访问的其他位置。

于 2010-07-03T11:24:23.227 回答