我对 Javascript 中的数组有疑问。我有一个将项目推送到数组的按钮。单击按钮后,不会执行旨在显示 div 中项目列表的 for 循环。
代码如下:
HTML:
<input type="text" id="tb">
<button id="btn">Submit</button>
<div id="list"></div>
Javascript:
var list = [];
btn.onclick = function(){
list.push(document.getElementById("tb").value);
}
for (var i in list){
document.getElementById("list").innerHTML = "<p>"+list[i]+"</p>"
}
有什么解决方案可以让我点击按钮后,div 更新项目列表,就像待办事项列表一样?
最佳答案
您可以在单击按钮时将 html 添加到列表中 - 请参见下面的演示:
btn.onclick = function() {
document.getElementById("list").innerHTML +=
"<p>" + document.getElementById("tb").value + "</p>"
}
<input type="text" id="tb">
<button id="btn">Submit</button>
<div id="list"></div>
如果您想像您在对此答案的评论中所说的那样将数组用作数据存储,您可以执行以下代码片段中给出的操作:
var list = [];
btn.onclick = function() {
// add to the list
list.push(document.getElementById("tb").value);
// TODO: save to local storage if needed
// reset the list
document.getElementById("list").innerHTML = '';
// display the list
for (var i in list) {
document.getElementById("list").innerHTML += "<p>" + list[i] + "</p>";
}
}
<input type="text" id="tb">
<button id="btn">Submit</button>
<div id="list"></div>
关于javascript - 如何将项目插入数组并将它们显示在 JavaScript 中的 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45618007/