为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

扬帆大鱼 2021-10-07 10:35:49
(我之前发布过这个问题,但我忘记添加一个缺失的元素,所以人们认为这是问题所在,但实际上并非如此,所以我再次发布了我应该首先使用的正确代码)我正在尝试制作一个待办事项应用程序,然后我想使用 aform和 an添加新的待办事项,event listener但是,当我完成代码时,该应用程序仅将书面文本添加到 ,object-array而实际上并未将其添加到 html 中的待办事项列表中页。我将在下面提供一个小代码来显示数组、设置代码和 html 以便使这个问题简短,但如果您想查看整个应用程序代码,请随时查看此 github 的存储库:https:/ /github.com/salahmak/Todo-application您还可以从此ngrok链接查看该应用程序的实时版本(我会一直保持到我解决问题为止):http: //7eb95c9a.ngrok.io编码:// The arrayconst 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" arraytodos.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>
查看完整描述

2 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

// 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);

})


document.querySelector('button').addEventListener('click', function(e) {

  e.preventDefault();

  var todo = document.querySelector('input').value;

  todos.push({

    text: todo,

    completed: false

  });   document.querySelector('#todo').insertAdjacentHTML('beforeend', '<p>' + todo + '</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>


查看完整回答
反对 回复 2021-10-07
  • 2 回答
  • 0 关注
  • 180 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信