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

Bri*_*old 7 variables jquery function hover

我试图在悬停时删除链接的标题属性,然后在鼠标移出时将其添加回来.我想将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);

});
Run Code Online (Sandbox Code Playgroud)

Mat*_*rym 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');

});
Run Code Online (Sandbox Code Playgroud)

诀窍是:

$.data(this, 'title');
Run Code Online (Sandbox Code Playgroud)

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


小智 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);

});
Run Code Online (Sandbox Code Playgroud)

  • 这是一个糟糕的解决方案......当分配悬停时,该变量肯定不会保持不变。 (3认同)