[英]setTimeout won't execute the function
我甚至看过这个,这个解决方案仍然没有帮助我: 在jquery中的X秒后执行一个函数
这是我的代码:
// featured bounce
$('#featured .animated').hover(function() {
$(this).addClass('bounce');
setTimeout( function(){
$(this).removeClass('bounce');},
1300
);
});
添加类有效,但是setTimeout考试不起作用。 它甚至不会执行,也不会在Chrome控制台中引发javascript错误。 我觉得我输入的内容都正确..在addClass()之后的.animated对象上的类如下所示:
“动画反弹”
动画播放,但它永远不会从类属性中删除“反弹”。
有帮助吗?
正确使用Function.prototype.bind ,可以避免像var that = this
廉价上下文黑客。
// featured bounce
$('#featured .animated').hover(function() {
var elem = $(this);
elem.addClass('bounce');
setTimeout(elem.removeClass.bind(elem, 'bounce'), 1300);
});
附注:Function.prototype.bind是ES5的补充,需要考虑浏览器支持。 请参阅有关该函数的MDN文章底部的兼容性表。
它的范围指向窗口,而不是您期望的元素。
$('#featured .animated').hover(function() {
var elem = $(this);
elem.addClass('bounce');
setTimeout( function(){
elem.removeClass('bounce');},
1300
);
});
$('#featured .animated').hover(function() {
$(this).addClass('bounce');
(function(that) {
setTimeout( function(){
// use `that` instead of `this`
$(that).removeClass('bounce');
}, 1300);
})(this); //pass `this` into this function
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.