Javascript jquery回调未定义数组
我得到一个错误,说json数组“tweets”在动画回调中未定义Javascript jquery回调未定义数组,javascript,jquery,json,Javascript,Jquery,Json,我得到一个错误,说json数组“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() {
$.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);
});
}
}
});
$.getJSON('php/engine.php',函数(tweets){
如果(tweets.length!=0){
对于(var i=0;i'+
“”+推特[i]['text']+'”)。动画({opacity:1},2000);
});
}
}
});
您遇到了一个关闭问题,以下是解决方法:
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
}
不应该这样。可能错误在于,
tweets[i]
未定义,这可能是因为您没有进行闭包。闭包是什么意思?可能是重复的
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);
});