提问人:Dela Torre 提问时间:7/7/2022 更新时间:7/8/2022 访问量:50
如何将一个类应用于嵌套数组内的所有元素,但在将同一类应用于下一个嵌套数组之前有一个间隔?
How can i apply a class to all elements inside a nested array but with an interval before apply the same class to the next nested array?
问:
我今天的目标是将一个类应用于嵌套数组内的所有元素,并等待 1 秒的延迟,然后再将同一类应用于下一个嵌套数组的所有元素,并删除应用于前一个嵌套数组的类。目前,我的类同时应用于所有嵌套数组的所有元素。这是我的代码所能达到的,因为我不知道如何继续。任何关于如何寻找以JavaScript或Jquery解决此问题的帮助将不胜感激。
let sequencing = [["01-01", "02-01", "03-01"],["01-02", "02-02", "03-02"],["01-03", "02-03", "03-03"],["01-04", "02-04", "03-04"]];
// This loop is for outer array
for (let i = 0; i < sequencing.length; i++) {
// console.log(sequencing[i]);
// This loop is for inner-arrays
for (var j = 0; j < sequencing[i].length; j++) {
//console.log(sequencing[j]);
// Accessing each elements of inner-array
$("#"+sequencing[i][j]).addClass("up");
}
}
答:
1赞
Rory McCrossan
7/8/2022
#1
要执行所需的操作,可以使用将类的添加延迟几毫秒。还可以用于擦除上一组元素中的类。setTimeout()
nIteration * 1000
removeClass()
另请注意,以下示例中使用了 ,以使代码更加简洁。forEach()
let sequencing = [["01-01", "02-01", "03-01"],["01-02", "02-02", "03-02"],["01-03", "02-03", "03-03"],["01-04", "02-04", "03-04"]];
sequencing.forEach((arr, i) => {
setTimeout(() => {
$('.up').removeClass('up');
arr.forEach(id => $('#' + id).addClass('up'));
}, i * 1000);
});
.up {
background-color: #C00;
color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="01-01">01-01</div>
<div id="02-01">02-01</div>
<div id="03-01">03-01</div>
<div id="01-02">01-02</div>
<div id="02-02">02-02</div>
<div id="03-02">03-02</div>
<div id="01-03">01-03</div>
<div id="02-03">02-03</div>
<div id="03-03">03-03</div>
<div id="01-04">01-04</div>
<div id="02-04">02-04</div>
<div id="03-04">03-04</div>
0赞
Twisty
7/8/2022
#2
请考虑以下几点。
$(function() {
var sequencing = [
["01-01", "02-01", "03-01"],
["01-02", "02-02", "03-02"],
["01-03", "02-03", "03-03"],
["01-04", "02-04", "03-04"]
];
$.each(sequencing, function(i, part) {
setTimeout(function() {
$.each(part, function(j, id) {
$("#" + id).addClass("up")
});
}, i * 1000);
});
});
.up {
border: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="01-01">
01-01
</div>
<div id="02-01">
02-01
</div>
<div id="03-01">
03-01
</div>
<div id="01-02">
01-02
</div>
<div id="02-02">
02-02
</div>
<div id="03-02">
03-02
</div>
<div id="01-03">
01-03
</div>
<div id="02-03">
02-03
</div>
<div id="03-03">
03-03
</div>
<div id="01-04">
01-04
</div>
<div id="02-04">
02-04
</div>
<div id="03-04">
03-04
</div>
这将为每次迭代创建一个唯一的超时。第一次通过时,超时为 (0 * 1000),然后是 (1 * 1000),以此类推......0
1000
这将为每次迭代的异步执行创建正确的暂停时间。
评论