jquery hover将变量传递给回调函数

时间:2010-06-09 18:54:30

标签: jquery function variables hover

我正在尝试在悬停时删除链接的title属性,然后在鼠标移出时将其添加回来。我想将var hoverText传递给悬停...

这是我的代码。有什么想法吗?

$(".icon a").hover(function() {
  $this = $(this);
  var hoverText = $.data(this, 'title', $this.attr('title'));                             
  $(this).find("em").animate({opacity: "show", top: "-35"}, "slow");
  $(this).find("em").text(hoverText);       

  $this.removeAttr('title');       


}, function(hoverText) {             

  $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");     
  $(this).attr("title", hoverText);

});

2 个答案:

答案 0 :(得分:6)

$(".icon a").hover(function() {
  $this = $(this);
  $.data(this, 'title', $this.attr('title'));                             
  $(this).find("em").animate({opacity: "show", top: "-35"}, "slow");
  $(this).find("em").text(hoverText);       

  $this.removeAttr('title');       


}, function(hoverText) {             

  $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");     
  $(this).attr("title", $.data(this, 'title');

});

诀窍是:

$.data(this, 'title');

当您使用数据时,您有效地将变量存储在该dom元素上,以用于您刚刚描述的明确目的。你也可以通过在你的初始悬停函数之上声明$ this变量来解决问题,扩展范围以涵盖两者。

答案 1 :(得分:1)

将“hoverText”作为全局变量。

var hoverText = '';
$(".icon a").hover(function() {
  $this = $(this);
  hoverText = $.data(this, 'title', $this.attr('title'));                             
  $(this).find("em").animate({opacity: "show", top: "-35"}, "slow");
  $(this).find("em").text(hoverText);       

  $this.removeAttr('title');       


}, function() {             

  $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");     
  $(this).attr("title", hoverText);

});
相关问题