Javascript:对于vs jQuery.each()有时间延迟 [英] Javascript: for vs jQuery.each() with time delay

查看:101
本文介绍了Javascript:对于vs jQuery.each()有时间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图1

for (var i = Things.length - 1; i >= 0; i--) {
    setTimeout(function(){
        // do something with Things[i]
    }, 200 * i);
};

图2

$(".things").each(function(i,o){
    setTimeout(function(){
        //do something with o
    }, 200 * i);
});

为什么图2工作但图1没有?每次我尝试第一种方法 i 总是等于 -1 。给出了什么?

Why does figure 2 work but figure 1 doesn't? Every time I try the first method i always equals -1. What gives?

推荐答案

for (var i = Things.length - 1; i >= 0; i--) {
    (function(i){
        setTimeout(function(){
          // do something with Things[i]
        }, 200 * i);
    })(i)
};

您需要为创建一个范围我 ,所以它保持其价值。否则它会通过循环更新。

You need to create a scope for i, so it maintains its value. Otherwise it gets updated with the loop.

它适用于图2的原因( $。each(function(i,o){.. 。}))因为这里的匿名函数正在为 i 创建一个闭包。

The reason it works for figure 2 ($.each(function(i,o){...})) is because the anonymous function here is creating a closure for i.

这篇关于Javascript:对于vs jQuery.each()有时间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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