好的,我解决了你的问题。这是您发送给我的代码(部分粘贴):
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("demonew2.json",function(data){
$.each(data,function(key,value){
$("#topmost").append('<div>'+key+'</div>');
if(data.hasOwnProperty(key)){
//alert(key);
var total = new Array();
for(var i=0; i<4; i++){ // Here 4 should be something like counts of the keys, as in this json file it is 4
total[i] = key;
$("#topmost").append('<div>'+total+'</div>');
setInterval (function(){alert(key)},5000);
// I NEED THE DATA TO BE LOADED KEY BY KEY, SAY AFTER PAGE LOAD IT WILL DISPLAY THE VALUES OF key_1, THEN AFTER 5 SECONDS<br />
// IT SHOULD DISPLAY key_2 VALUES AND SO ON.
}
}
});
});
});
</script>
</head>
<body>
<div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>
</body>
您的代码中有两个主要问题:
1)如果您希望在延迟后完成作业,则必须使用“setTimeout”而不是“setInterval”以给定间隔重复作业。2)对所有作业使用相同的延迟量将迫使它们几乎在同一时刻完成,因此您必须增加延迟量。
此外,将值直接传递给 setTimeout 或 setInterval 方法并不是一个好主意,因为它们会启动一个新线程并且跨线程值注入可能会出现异常行为,因此我更喜欢使用代理函数来避免直接注入所以这是最终的工作代码:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("demonew2.json", function (data) {
var delay = 0;
$.each(data, function (key, value) {
delay += 5000;
showData(key, value, delay);
});
});
});
function showData(key, value, delay) {
setTimeout(function () {
$("#topmost").append('<div>' + key + " = " + JSON.stringify(value) + '</div>');
}, delay);
}
</script>
</head>
<body>
<div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>
</body>
所以让我知道这是否解决了你的问题。玩得开心。;)
更新:我添加了完整的页面代码供您轻松使用,还稍微更改了附加部分以具有淡入淡出效果并使其更有趣:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("demonew2.json", function (data) {
var delay = 0;
$.each(data, function (key, value) {
delay += 5000;
showData(key, value, delay);
});
});
});
function showData(key, value, delay) {
setTimeout(function () {
$("#topmost").fadeOut(function() {
$("#topmost").append('<div>' + key + " = " + JSON.stringify(value) + '</div>').fadeIn();
});
}, delay);
}
</script>
</head>
<body>
<div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>
</body>
</html>