从这个变化:
setTimeout(hide(this),2000);
这样:
var self = this;
setTimeout(function() {
hide(self);
},2000);
您立即调用这个函数,它的返回值传递给setTimeout
而不是将函数引用传递给可以稍后调用的setTimeout
。请记住,(xx)
意味着立即执行。所以hide(this)
意味着现在执行它,而不是更晚。另一方面,function() { hide(this); }
是可以稍后调用的函数引用。
或者,如果你不使用隐藏功能其他地方,那么你就可以在这样的整合是:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
var self = this;
setTimeout(function() {
$(self).remove();
},2000);
});
一个有用的语言功能是.bind()
可以使用以“硬连线”this
的值或回调函数的参数值。例如,你可以这样做:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
setTimeout(function() {
$(this).remove();
}.bind(this),2000);
});
的.bind(this)
套this
当前值是this
值时,调用回调函数。
或者,如果你仍然有功能hide(item)
,那么你可以使用.bind的参数设置为hide()
这样的:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
setTimeout(hide.bind(null, this)), 2000);
});
或者,你可以使用动画,让它提供为您的时机:
$(".addtimer div").click(function(){
$(this).toggleClass("remove").delay(1000).slideUp(1000, function() {
$(this).remove();
});
});
正如你可以看到,有很多的选择,并且在使用视情况而定了一下,你觉得是什么让最清晰的代码我ñ你的情况和你最舒服的使用方式。
谢谢你,知道有一个更好的办法 – Skylark 2015-02-07 17:57:35
增加了其他两个选项的答案。 – jfriend00 2015-02-07 18:04:01
使用var self = this;'因为他使用的是jQuery,所以我会选择['.proxy'](http://api.jquery.com/jquery.proxy/)。否则,我会使用'bind'或'closure'(我相信'proxy'用于跨浏览器的目的)。 – Xotic750 2015-02-07 18:56:34