jQuery在for循环中延迟行为 [英] jQuery deferred behaviour in for loop

查看:648
本文介绍了jQuery在for循环中延迟行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近问了一个有关for循环中延迟的jquery行为的问题. 在此处链接

I recently asked a question about the behaviour of jquery deferred in a for loop. Link here

我收到了有效的答案,但我不明白为什么会起作用.

I received a working answer but I don't understand why it works.

如果我有以下代码:

function update(callbacks) {
    return $.Deferred(function(dfr) {
        setTimeout(function() {
            callbacks.success()
        }, 1000);
        dfr.resolve();
    }).promise();
}

function updateElements(deferreds) {
    for (var i = 0; i < 5; i++) {
        (function() {
            var index = i;
            deferreds.push(update({
                success: function() {
                    alert(index);
                }
            }));
        })();
    }
};

(function() {
    var deffereds = [];
    updateElements(deffereds);
    $.when.apply($, deffereds).then(function() {}, function() {});
})();​

它返回5个警报窗口,值从0到4.如果我将updateElements方法更改为:

It returns 5 alert windows with the values 0 through to 4. If I change the updateElements method to:

function updateElements(deferreds) {
    for (var i = 0; i < 5; i++) {
        var index = i;
        deferreds.push(update({
            success: function() {
                alert(index);
            }
        }));
    }
};

它返回5个仅值为4的警报窗口.有人可以解释一下这种行为吗?我正在努力了解差异的来源.

It returns 5 alert windows with the value 4 only. Could someone please explain this behaviour? I'm struggling to understand where the difference comes about.

谢谢!

推荐答案

之所以这样做,是因为您已使用

The reason that it does that is because you have closed over a loop with

(function() {
        var index = i;
        deferreds.push(update({
            success: function() {
                alert(index);
            }
        }));
})();

此自执行块变成静态值,因为它没有传入任何外部值.在链接的答案中,您需要传入该值.请注意,在值的末尾给出关键区别IEFE(立即执行的函数表达式).抱歉,请注意上限.

This self executing block turns into a static value because it has no external values passed in. As in the answer you linked, you need to pass that value in. Note the key difference where the value is given at the end of the IEFE (immediately executed function expression). Sorry for the caps, but this needs emphasis.

(function(VALUE_ACCEPTED){
  //VALUE_ACCEPTED accepts the passed value of VALUE_PASSED
})(VALUE_PASSED)

这样您的代码就会变成这样:

So that your code becomes this:

function updateElements(deferreds) {
for (var i = 0; i < 5; i++) {
    (function(valueAccepted) { // valueAccepted = the passed in value from i
        var index = valueAccepted;
        deferreds.push(update({
            success: function() {
                alert(index);
            }
        }));
    })(i); // pass in i to valueAccepted
 }
};

这篇关于jQuery在for循环中延迟行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆