jQuery语法错误 [英] Error in jquery syntax

查看:109
本文介绍了jQuery语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This code is supposed to produce the following effect: when .expander is moused over, it waits 400 milliseconds and then expands to 150% of its original size over the course of 270 milliseconds. If the mouse leaves .expander, the expansion is cancelled.

<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时,它会增长.因此,代码的第二部分必须没问题.有人看到第一部分有任何问题吗?

When I mouse over .expander, nothing happens. However, when my mouse leaves .expander, it grows. So the second part of the code must be fine. Does anyone see any problems with the first part?

推荐答案

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

You are loosing context this inside setTimeout. You can use Function.prototype.bind to bind callback function to proper context:

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

如果您关心IE8支持,请使用 $.proxy -简单的绑定实现. /p>

If you care about IE8 support, use $.proxy - simple bind implementation.

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

这篇关于jQuery语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆