首页 > 解决方案 > 如何使用事件侦听器向对象数组添加新元素并将其显示在 html 页面上(编辑代码)

问题描述

(我之前发布过这个问题,但是我忘记添加一个缺失的元素,所以人们认为这是问题所在,但实际上并非如此,所以我再次使用我应该首先使用的正确代码再次发布)

我正在尝试制作一个todo 应用程序,然后我想使用 aform和 an添加新的 todoevent listener但是,当我完成代码时,该应用程序仅将书面文本添加到 中object-array,而实际上并没有将其添加到 html 中的 todos 列表中页。

我将在下面提供一个小代码,显示数组、设置代码和 html,以使这个问题简短,但如果你想查看整个应用程序代码,请随时查看这个 github 的存储库:https:/ /github.com/salahmak/Todo-application

您还可以从此ngrok链接查看应用程序的实时版本(我会一直保持它直到我解决问题):http: //7eb95c9a.ngrok.io

编码:

// The array
const todos = [{
  text: 'wake up',
  completed: true
}, {
  text: 'get some food',
  completed: true
}, {
  text: 'play csgo',
  completed: false
}, {
  text: 'play minecraft',
  completed: true
}, {
  text: 'learn javascript',
  completed: false
}];


//creating p elements and assigning their text content to each "text" property of the "todos" array

todos.forEach(function(todo) {
  let p = document.createElement('p');
  p.textContent = todo.text;
  document.querySelector('#todo').appendChild(p);
})
<h1>Todos</h1>
<div id="todo"></div>
<form id="form">
  Add a new todo
  <input type="text" placeholder="Type your first name" name="firstName">
  <button>Submit</button>
</form>

标签: javascripthtmlarraysobjectdom

解决方案


试试这个(添加元素后更新 DOM):

 document.querySelector('#form').addEventListener('submit', function(e) {
      e.preventDefault();
      let newObject = { text: e.target.elements.firstName.value, completed: false };
      todos.push(newObject);
      renderTodos(todos, filters);
    });

这是完整的小提琴示例: https ://jsfiddle.net/9j2nky6q/


推荐阅读