setTimeout 函数未按预期工作。这是我的代码:
$(document).delegate('.pur','click', function(e){
var productid = $(this).attr('id');
var quantity = $('#qua').val();
if(quantity>0){
this.value='Adding';
}
else{
this.value='Min 100';
setTimeout(function(){this.value='Buy now'}, 3000);
}
});
Run Code Online (Sandbox Code Playgroud)
上面的代码根本不起作用,它不会像预期的那样在 3 秒后更改值。有什么缺陷或者什么东西在里面吗?任何人都可以帮助找出问题所在吗?
范围问题
在 setTimeout 内部,“this”与 setTimeout 外部引用的对象不同。
像这样修复它
$(document).delegate('.pur','click', function(e){
var productid = $(this).attr('id');
var quantity = $('#qua').val();
if(quantity>0){
this.value='Adding';
}
else{
this.value='Min 100';
var that = this; // hold a reference to "this" as "that"
setTimeout(function(){that.value='Buy now'}, 3000); // use "that" instead of "this"
}
});
Run Code Online (Sandbox Code Playgroud)
匿名函数中对“this”的引用并不指向任何东西。您可以像这样更改它(即,self成为匿名函数可见范围内的变量):
this.value='Min 100';
var self = this;
setTimeout(function(){self.value='Buy now'}, 3000);
Run Code Online (Sandbox Code Playgroud)