jquery .attr()问题

and*_*rei 3 jquery attr

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

$(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});
  })
});
Run Code Online (Sandbox Code Playgroud)

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

$('a').hover(function() {
  $(this).attr('title', '');
});
Run Code Online (Sandbox Code Playgroud)

问题是我无法添加它.我试过了:

$(this).attr('title', title) //from my title variable
Run Code Online (Sandbox Code Playgroud)

但它失败了.建议?

use*_*716 6

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

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

var $th = $(this);

$th.data( 'prevTitle', $th.attr('title') );
Run Code Online (Sandbox Code Playgroud)

然后在需要时访问它(可能是你的下一个悬停功能).

var $th = $(this);

$th.attr('title', $th.data( 'prevTitle' ));
Run Code Online (Sandbox Code Playgroud)

您可以将变量声明置于两个函数之外.

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();
});
Run Code Online (Sandbox Code Playgroud)

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