jquery语法错误

此代码应该产生以下效果:当.expander被鼠标hover时,它会等待400毫秒,然后在270毫秒的时间内扩展到其原始大小的150%。 如果鼠标离开.expander ,则取消扩展。

 
$(".expander").on('mouseenter', function () { $.data(this, 'timer', setTimeout(function () { $(this).stop(true, true).animate({width: "150%"}, 270, function() {}); }, 400)); }).on('mouseleave', function() { clearTimeout($.data(this, 'timer')); $(this).stop(true, true).animate({width: "150%"}, 270, function() {}); });

当我将鼠标移到.expander ,没有任何反应。 但是,当我的鼠标离开.expander ,它会增长。 因此代码的第二部分必须正常。 有没有人看到第一部分有任何问题?

你在setTimeout中丢失了this上下文。 您可以使用Function.prototype.bind将回调函数绑定到正确的上下文:

 $.data(this, 'timer', setTimeout(function () { $(this).stop(true, true).animate({ width: "150%" }, 270, function () {}); }.bind(this), 400)); 

如果您关心IE8支持,请使用$.proxy – 简单绑定实现。

 $.data(this, 'timer', setTimeout($.proxy(function () { $(this).stop(true, true).animate({ width: "150%" }, 270, function () {}); }, this), 400));