我正在尝试使用setTimeout在特定时间后更改一些课程,但我得到的只是即时更改,而无需等待 2 秒。我做错了什么?
这是JS
function addElements() {
var data = ["empty","typeA","typeB","typeC"];
for(var k=0;k<data.length;k++) {
var set=document.getElementById("empty");
set.setAttribute("id", "empty"+k);
if(data[k] !== "empty") {
var s = set.setAttribute("class", data[k]);
setTimeout(function() { s; }, 2000);
}
else set.setAttribute("class", data[k]);
}
}
和 HTML
<a href="#" onclick="addElements()">Start</a>
<div id="empty" class="empty"></div>
<div id="empty" class="empty"></div>
<div id="empty" class="empty"></div>
<div id="empty" class="empty"></div>
更正了 JS,以防有人错误地需要它
function addElements() {
var time = 0;
var data = ["empty","typeA","typeB","typeC"];
for(var k=0;k<data.length;k++) {
var set=document.getElementById("empty");
set.setAttribute("id", "empty"+k);
var cName = data[k];
if(cName !== "empty") {
time += 2000;
(function(set, cName ) {
setTimeout(function() {
set.setAttribute("class", cName );
}, time);
})(set, cName);
}
}
}