尝试让元素每x秒更改一次。当我单击按钮时,它应该更改innerHTML,循环遍历数组。下面的代码更改了文本,但显示了数组中的最后一个结果。
<h1 id="header">Agent</h1>
<button id="change-header" onclick="loopHeader()">Click Me</button>
<script>
function loopHeader() {
var loopHeader = setInterval(changeText, 1000);
}
function changeText() {
var headers = ["Agent", "Expert", "Homes", "Service", "Results"];
var text = "";
var i = 0;
var x = document.getElementById("header");
for (i = 0; i < headers.length; i++) {
text = headers[i];
x.innerHTML = text;
}
}
</script>
答案 0 :(得分:1)
将计数移到函数外部,然后继续循环并在结束时重置为0.
function loopHeader() {
var loopHeader = setInterval(changeText, 1000);
}
var headers = ["Agent", "Expert", "Homes", "Service", "Results"];
var loopItem = 0;
function changeText() {
loopItem++;
if (loopItem == headers.length) {
loopItem = 0;
}
document.getElementById("header").innerHTML = headers[loopItem];
}
</script>
&#13;
<div id="header">
</div>
<button id="change-header" onclick="loopHeader()">Click Me</button>
&#13;
答案 1 :(得分:0)
那是因为每次调用changeText
时,它都会开始通过数组中的文本从索引0到结尾更改按钮的innerHTML
(It&#39; s发生的事情,你无法看到它,因为它发生得很快)。你需要的是在函数外部定义i
,并且每次调用函数增量i
并在没有循环的情况下从数组中显示其对应的值。像这样:
<button id="change-header" onclick="loopHeader()">Click Me</button>
<script>
function loopHeader() {
// if you want to start the animation just after the button is clicked, then uncomment the next line
// changeText();
var loopHeader = setInterval(changeText, 1000);
}
var i = 0; // i declared outside with the initiale value of 0
var headers = ["Agent", "Expert", "Homes", "Service", "Results"]; // this also should be outside (what's the point of redefining it every time the function is called)
function changeText() {
var x = document.getElementById("change-header"); // the id is change-header
// increment i and check if its beyond the boundaries of the loop, or just use modulo operator t prevent it from going beyond
i = (i + 1) % headers.length;
x.textContent = headers[i]; // textContent is better than innerHTML
}
</script>
&#13;