jquery回调未定义的数组

时间:2013-05-10 16:09:54

标签: javascript jquery json

我收到一条错误,说json array" tweets"在动画回调中未定义...

    $.getJSON('php/engine.php', function(tweets){

        if (tweets.length != 0) {

            for (var i = 0; i < tweets.length; i++) {

                $('#1').animate({opacity: 0}, 2000, function() {

                    $(this).css('background-color', 'red').html(

                        '<p><span class="profile_image">' + tweets[i]['profile_image_url'] + '</span>' +
                        '<span class="name">' + tweets[i]['name'] + '</span>' + 
                        '<span class="mention">' + tweets[i]['screen_name'] + '</span></p>' +
                        '<p><span class="text">' + tweets[i]['text'] + '</span></p>').animate({opacity: 1}, 2000);

                }); 
            }
        }

    });

1 个答案:

答案 0 :(得分:2)

你有一个关闭问题,这是如何解决它:

for (var i = 0; i < tweets.length; i++) {
    (function (real_i) {
        $('#1').animate({opacity: 0}, 2000, function() {
            console.log(tweets[real_i]);
        });
    }(i)); // <-- immediate invocation
}

很快就会调用animate-callback,之后i的值为tweets.lengthtweets[tweets.length]未定义。

另一个更简单的解决方案是使用map-function而不是for,然后闭包是免费的。

function map(array, callback) {
    for (var i = 0; i < array.length; i += 1) {
        callback(array[i], i);
    }
}

map(tweets, function (value, index) { // value and index are already 'closed' to this scope
    console.log(value);
});