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

Keep different variable's state in multiple anonymous asynchronous functions in a loop

本文关键字:函数 异步 循环 状态 变量      更新时间:2023-09-26

我不知道如何在没有代码的情况下描述它,所以它开始了:

$('.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)
    );
});

查看代理

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