我为我的链接编写了这个快速工具提示功能:
$(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
但失败了。建议?
答案 0 :(得分: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()
会更安全。
答案 1 :(得分:2)
您的标题变量仅存在于第一个处理程序的范围内。您必须将值存储在可从第二个处理程序访问的其他位置。