gpt4 book ai didi

javascript - 如何使用事件监听器向对象数组添加新元素并将其显示在 html 页面上(已编辑代码)

转载 作者:可可西里 更新时间:2023-11-01 13:18:39 25 4
gpt4 key购买 nike

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

我试图制作一个待办事项应用程序,然后我想使用表单事件监听器添加新的待办事项,但是,当我完成了应用程序仅将书面文本添加到 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>

最佳答案

试试这个(添加元素后更新 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);
});

这是完整的 fiddle 示例:https://jsfiddle.net/9j2nky6q/

关于javascript - 如何使用事件监听器向对象数组添加新元素并将其显示在 html 页面上(已编辑代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57813454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com