gpt4 book ai didi

javascript - 循环遍历数组文本没有响应

转载 作者:行者123 更新时间:2023-12-03 03:24:10 24 4
gpt4 key购买 nike

document.getElementById("changeText").addEventListener("click", function(){
var text = ["This", "is", "a", "secret", "message"];
for (var counter=0; counter < text.length-1; counter++) {
document.getElementById("heading").innerText = text[counter];

}
});
<h1 id="heading">This heading will change</h1>
<button id="changeText">change text</button>

你可能知道,也可能不知道,但我刚刚开始接触 Javascript,正在练习一些概念。

其背后的想法是,当用户单击按钮时,它会循环遍历数组并用数组的每个元素替换 h1 内部文本。但是,当我单击按钮时,替换内部 HTML 的唯一元素是数组的 text[3],这当然是“ secret ”的。

为什么会发生这种情况?请记住,我是 Javascript 新手,仍在学习中。据我所知,我已声明计数器从 0 开始,并在达到数组长度 - 1 时将其停止,并且每次将其递增 1。不确定我在这里做错了什么。请帮忙。

最佳答案

该代码中有两个单独的问题:

  1. 您太早停止循环了。应该是< text.length<= text.length - 1但不是< text.length - 1 .

  2. 在下一次更新元素文本之前,您不会给浏览器重绘元素的机会。您可以使用setTimeout做到这一点。

这是一个处理两者的示例,请参阅 ***评论:

// *** A function we use to update the text
function updateText(el, thisText) {
el.textContent = thisText;
}

document.getElementById("changeText").addEventListener("click", function(){
var text = ["This", "is", "a", "secret", "message"];
// *** Look up the element *once*
var el = document.getElementById("heading");
// *** Use "< text.length"
for (var counter=0; counter < text.length; counter++) {
// *** Schedule a timed callback
setTimeout(
updateText, // *** The function to call
counter * 500, // *** Delay before calling, each is 500ms later than previous
el, text[counter] // *** Arguments for the timer to pass the function
);
}
});
<h1 id="heading">This heading will change</h1>

<button id="changeText">change text</button>

上面还有其他更改:

  • textContent而不是innerText 。如果支持较旧的 IE,您可能需要进行功能检测以查看要使用哪个。或者对于您的消息,您可以设置 innerHTML相反。
  • 请注意避免在循环中创建函数,因为我们只需要一个函数。

关于javascript - 循环遍历数组文本没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46428834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com