jquery 语法错误

Error in jquery syntax

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

<div class="expander"><%=image_tag("expander.jpg")%></div>
<script type="text/javascript">
  $(".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() {});
  });
</script>

当我将鼠标悬停在 .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));