gpt4 book ai didi

javascript - setTimeout 函数中的变量 (jQuery)

转载 作者:数据小太阳 更新时间:2023-10-29 03:59:41 24 4
gpt4 key购买 nike

我试图在 setTimeout 函数中使用 jQuery 语句,但是我不让它工作。我尝试了很多变体,比如这个(我使用 'this' 因为 setTimeout 在每个函数中,并且选择器被缓存/存储在一个对象中,因此是 $selector):

setTimeout("" + this.$selector + ".val('" + this.savVal + "')", 1);

我要怎么写这个?

谢谢!

最佳答案

当调用 setTimeout 时需要保留当前的 ​​this 项时使用此结构:-

setTimeout((function(self) {
return function() { $selector.val(self.savVal) };
})(this), 1);

这从外部函数执行上下文创建了一个闭包。外部函数返回一个内部函数,该函数可以访问 self 参数。它是在超时发生时调用的内部函数,但 self 的值将保留原始 this 值。

关于javascript - setTimeout 函数中的变量 (jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1673621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com