猿问

如何使用事件侦听器向对象数组添加新元素并将其显示在 html 页面上

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


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


我将在下面提供一个小代码来显示数组、设置代码和 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>


扬帆大鱼
浏览 181回答 2
2回答

qq_笑_17

// The arrayconst todos = [{&nbsp; text: 'wake up',&nbsp; completed: true}, {&nbsp; text: 'get some food',&nbsp; completed: true}, {&nbsp; text: 'play csgo',&nbsp; completed: false}, {&nbsp; text: 'play minecraft',&nbsp; completed: true}, {&nbsp; text: 'learn javascript',&nbsp; completed: false}];//creating p elements and assigning their text content to each "text" property of the "todos" arraytodos.forEach(function(todo) {&nbsp; let p = document.createElement('p');&nbsp; p.textContent = todo.text;&nbsp; document.querySelector('#todo').appendChild(p);})document.querySelector('button').addEventListener('click', function(e) {&nbsp; e.preventDefault();&nbsp; var todo = document.querySelector('input').value;&nbsp; todos.push({&nbsp; &nbsp; text: todo,&nbsp; &nbsp; completed: false&nbsp; });&nbsp; &nbsp;document.querySelector('#todo').insertAdjacentHTML('beforeend', '<p>' + todo + '</p>');});<h1>Todos</h1><div id="todo"></div><form id="form">&nbsp; Add a new todo&nbsp; <input type="text" placeholder="Type your first name" name="firstName">&nbsp; <button>Submit</button></form>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答