JavaScript回调函数中的变量范围 [英] scope of variables in JavaScript callback functions

查看:102
本文介绍了JavaScript回调函数中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望下面的代码提醒0和1,但它会两次提醒2。我不明白原因。不知道这是不是jQuery的问题。此外,如果不准确,请帮助我修改此帖子的标题和标签。

I expected the code below to alert "0" and "1", but it alert "2" twice. I don't understand the reason. Don't know if it is a problem of jQuery. Also, please help me to edit title and tags of this post if they are inaccurate.

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                for (var i=0; i<2; i++) {
                    $.get('http://www.google.com/', function() {
                        alert(i);
                    });
                }
            });
        </script>
    </head>
    <body>
    </body>
</html>


推荐答案

您正在分享单个 i 所有回调中的变量。

You're sharing the single i variable among all of the callbacks.

因为Javascript闭包通过引用捕获变量,所以回调将始终使用当前值。因此,当jQuery在循环执行后调用回调时, i 将始终为 2

Because Javascript closures capture variables by reference, the callbacks will always use the current value of i. Therefore, when jQuery calls the callbacks after the loop executes, i will always be 2.

您需要引用 i 作为单独函数的参数。

You need to reference i as the parameter to a separate function.

例如:

function sendRequest(i) {
    $.get('http://www.google.com/', function() {
        alert(i);
    });
}

for (var i = 0; i < 2; i++) {
    sendRequest(i);
}

这样,每个回调都有一个单独的闭包,带有一个单独的 i 参数。

This way, each callback will have a separate closure with a separate i parameter.

这篇关于JavaScript回调函数中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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