嘿傢伙誰可以幫助我出去? 基本上我想創建一個突發新聞頁腳,通過newsWire數組循環並自動更新文本。問題是當我在loadNewswire函數外部運行我的console.log(newsWire.length)時,它返回0,而console.log裏面返回40,因爲它應該是?全球陣列沒有更新後.push內功能
鏈接:http://jsfiddle.net/u8y8zh72/3/
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<style>
footer {
height: 75px;
position: fixed;
bottom: 0;
}
</style>
</head>
<body>
<div class="container">
<ul id="js-news" class="js-hidden"></ul>
</div>
<footer>
<div class="container" id="newswiretxt">
<span></span>
</div>
</footer>
</body>
<script type="text/javascript">
var newsWire = [];
function loadNewswire() {
$.getJSON('http://api.nytimes.com/svc/news/v3/content/all/all.json',
{'api-key': 'XXXXXXXXX'},
function(data) {
console.log(data)
var newsWireTemp = [];
for (var i = 0; i < data.results.length; i++) {
var breakingNews = data.results[i];
var breakingTitle = breakingNews.title;
var breakingAbstract = breakingNews.abstract;
newsWireTemp.push(breakingTitle);
newsWireTemp.push(breakingAbstract);
}
newsWire = newsWireTemp;
console.log(newsWire.length);
});
}
loadNewswire();
console.log(newsWire.length);
$(document).ready(function() {
var items = newsWire;
$text = $('#newswiretxt span'),
delay = 10; //seconds
function loop (delay) {
$.each(items, function (i, elm){
$text.delay(delay*1E3).fadeOut();
$text.queue(function(){
$text.html(items[i]);
$text.dequeue();
});
$text.fadeIn();
$text.queue(function(){
if (i == items.length -1) {
loop(delay);
}
$text.dequeue();
});
});
}
loop(delay);
});
</script>
'loadNewswire()'進行異步調用。這意味着'console.log(newsWire。長度);'在回調之前運行('newsWire = newsWireTemp;')。你可以知道,因爲'console.log(newsWire.length)'正在輸出'console.log(newsWire.length);' –