我想从json数组中给出一个带有 id 的项目,让该类处于活动状态。但是在数组中的秒之后,它应该让该类活动的下一个项目。所以继续循环。
的index.html
<div id="5"></div>
<div id="8"></div>
<div id="11"></div>
Scheme.json:
[
{
"id":"5",
"seconds":"3"
},
{
"id":"8",
"seconds":"2"
},
{
"id":"11",
"seconds":"4"
}
]
的script.js:
function loop() {
$.getJSON("assets/scheme.json", function(data) {
//
});
}
答案 0 :(得分:0)
这样的事情会这样做 - 使用setTimeout
有选择地添加类,并在完成后调用下一个项目
var data = [
{
"id":"5",
"seconds":"3"
},
{
"id":"8",
"seconds":"2"
},
{
"id":"11",
"seconds":"4"
}
];
// put everything below here inside your callback from getJSON
function setActive(data, index){
let item = data[index];
setTimeout(function(){
$('#' + item.id).addClass("active");
if(index<data.length-1)
setActive(data,index+1);
}, item.seconds*1000)
}
// start execution at the first item
setActive(data,0);
&#13;
.active{ background-color: red}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="5">Five</div>
<div id="8">Eight</div>
<div id="11">Eleven</div>
&#13;
答案 1 :(得分:0)
你只需要累积项目之间的秒数
function loop() {
$.getJSON("assets/scheme.json", function(data) {
var seconds = 0;
for (let i=0; i<data.length; i++) {
seconds += data[i].seconds * 1000;
setTimeout(function(){ setActive(data[i].id)}, seconds );
}
}
}
答案 2 :(得分:0)
//take off class active
function unactive(){
$(".active").removeClass("active");
}
//add class active and continue recursive loop
function activate(current,data){
unactive();//unactive all before
$('#'+data[current].id).addClass("active");
current++;
if (current<data.length){
setTimeout(activate.bind(this,current,data),parseInt(data[current].seconds)*1000);//run again
}else{
//here is end but we can start again from 0
setTimeout(startActive.bind(this,data),parseInt(data[current-1].seconds)*1000)
}
};
//starts our loop
function startActive(data){
var current=0;
setTimeout(activate.bind(this,current,data),parseInt(data[current].seconds)*1000);
};
//data from json
var fromJson=[
{
"id":"5",
"seconds":"3"
},
{
"id":"8",
"seconds":"2"
},
{
"id":"11",
"seconds":"4"
}
];
//run
startActive(fromJson);
&#13;
.active{
background:orange;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="5">5</div>
<div id="8">8</div>
<div id="11">11</div>
&#13;
上面的代码从对象集合中获取数据(在您的代码集合中将来自ajax)并执行递归循环。我也在最后一个元素之后重复循环,一切都来自乞讨,如果这样的重复是不需要的,只需从激活函数中删除 else 。