问题
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