javascript - 如何将项目插入数组并将它们显示在 JavaScript 中的 div 中

标签 javascript html arrays

我对 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/

相关文章:

javascript - Jquery Tools 可滚动 onBeforeSeek 函数然后滑动到下一个

javascript - 选择元素javascript

html - IE 中的 SVG 垂直对齐问题

c - C 中的输入字符串数组内存管理

java - 数组的随机改组

javascript:在数组中存储多个变量

javascript - jQuery .index() 总是返回 1

javascript - 使用 gulp 检查根目录中所有 html 文件中的空链接或空白链接

Python 破折号 : Fitting a table and a graph in one row of a grid

javascript - jQuery - 如何在从 Ajax 检索数据后添加关闭按钮?