当值改变时,setTimeout函数不起作用

setTimeout function not working with value change

本文关键字:setTimeout 函数 不起作用 改变      更新时间:2023-09-26

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);
    }
});

上面的代码根本不起作用,它在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"
    }
});

匿名函数中对"this"的引用没有指向任何东西。您可以这样更改它(即,self是匿名函数可见性范围内的变量):

     this.value='Min 100'; 
     var self = this;
     setTimeout(function(){self.value='Buy now'}, 3000);

这应该也能奏效

setTimeout(function() { this.value = 'Buy now'; }.bind(this), 3000)