【问题标题】:jquery variable scope within function函数内的jquery变量范围
【发布时间】:2012-10-04 13:32:08
【问题描述】:
meclass.prototype.switch = function() {
var items = [];
$.getJSON('http://localhost/jsoner.php', function(data) {
    $.each(data, function(key, val) { 
        items.push(val);
        alert(items[0]); //this works

    });
});
alert(items[0]); //this does not
}

我一直在修补这个问题,但并没有真正理解它。我在我的所有 jquery 函数中都遇到了这个问题,所以这是我还没有学过的基本知识,也没有运气找到答案。

【问题讨论】:

  • items 数组在您尝试访问时为空。仅当您从服务器接收 JSON 对象时才会填充它。因此,在您的回调中一切正常。

标签: javascript jquery variables scope


【解决方案1】:

getJSON 方法是异步的。执行将立即继续执行以下语句。回调函数将在稍后服务器响应请求时执行。

因此,任何依赖异步请求结果的代码都需要在回调函数中移动。

这实际上是发生了什么:

var items = []; //Declare `items`, empty array
//Make AJAX request
alert(items[0]); //It's still an empty array
//Wait some arbitrary amount of time...

//AJAX request complete, run the callback function
alert(items[0]); //Inside callback, items now contains elements

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-06
    • 2016-10-26
    • 2011-10-27
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多