Error in jquery syntax

依然范特西╮ 提交于 2019-12-24 11:54:16

问题


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>

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/28892531/error-in-jquery-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!