gpt4 book ai didi

javascript - 在循环中的多个匿名异步函数中保持不同变量的状态

转载 作者:行者123 更新时间:2023-11-30 10:44:54 34 4
gpt4 key购买 nike

我不知道如何在没有代码的情况下描述它,所以这里是:

$('.colors').each(function() {
$.getJSON('my.json', function(data) {
$(this).css('color', data.color);
});
});

我希望 getJSON 回调的主体在父级(each 回调)范围内引用 this 的值。

此代码将不起作用,因为 this 将不是 getJSON 回调之外的内容。即使我尝试将它放在一个变量中,它也不会起作用,因为只有一个变量将被所有回调共享,而不是每次循环迭代共享一个变量。

我怎样才能做到这一点?

最佳答案

您可以在闭包中捕获它:

$('.colors').each(function() {
var $this = $(this);
$.getJSON('my.json', function(data) {
$this.css('color', data.color);
});
});

或:

$('.colors').each(function() {
$.getJSON(
'my.json',
(function(element) {
return function(data) {
element.css('color', data.color);
};
})(this)
);
});

关于javascript - 在循环中的多个匿名异步函数中保持不同变量的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8968661/

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