【发布时间】:2020-02-28 13:47:54
【问题描述】:
我正在为我工作的公司编写一个新闻显示,我正在尝试让页面在遍历整个 JSON 数组长度后刷新。目前一切正常,但我不完全确定刷新命令会去哪里。目前它所在的位置没有执行。这是我的相关代码:
var i = 0,
d = null,
x = null,
interval = 3000;
console.log('welcome');
$(document).ready(function(){
fetch();
console.log('fetching');
});
function fetch(){
// get the data *once* when the page loads
$.getJSON('info.json?ver=' + Math.floor(Math.random() * 100), function(data){
// store the data in a global variable 'd'
d = data[0];
console.log('results');
console.log(data);
// create a recurring call to update()
x = setInterval(function(){
update()
}, interval);
});
}
function update(){
console.log('update starting');
// if there isn't an array element, reset to the first once
if (d && !d[i]){
console.log('got the D');
clearInterval(x);
i = 0;
fetch();
return;
if(d[i] >= d.length){
// refresh the window if the variable is longer than the array
console.log('refreshing');
window.location.reload();
}
}
// remove the previous items from the page
$('ul').empty();
// add the next item to the page
$('ul').append(
'<li>' + d[i]['news']
+ '</li>'
);
// increment for the next iteration
i++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='news'>
<ul></ul>
</div>
【问题讨论】:
-
if(d[i] >= d.length){应该是if(i >= d.length){ -
我可以看到的第一件事是在同一个块中(在更新函数中获取后)有一个返回语句,后跟代码。所以 return 正在停止执行函数。
标签: javascript jquery html loops page-refresh