我正在尝试设置一个超时值,查看 this question我发现使用任何形式的 setTimeout(function(), int);
都会“跳过”计时器,我该如何处理下面的代码?
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
setTimeout(hide(this),2000);
});
function hide(name) {
$(name).remove();
}
输出
".addtimer div" disappears instantly
最佳答案
由此改变:
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();
});
});
如您所见,有很多选项,使用哪个在一定程度上取决于具体情况、您认为在您的情况下最清晰的代码以及您最习惯使用的内容。
关于javascript - setTimeout 中函数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28385426/