我得到一个错误说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() {
$(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);
});
}
}
});
你有一个闭包问题,下面是如何补救它:
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
}
动画回调在很长时间后才被调用,此时i
的值为tweets.length
, tweets[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);
});