gpt4 book ai didi

javascript - 如何从提交事件处理程序向对象数组添加新元素

转载 作者:行者123 更新时间:2023-11-28 14:15:13 25 4
gpt4 key购买 nike

编码员您好,我正在尝试制作一个简单的 javascript todo 应用程序,并且已经设置了一些内容,但现在我陷入了“如何从 addEventListener('” 的对象 todos 数组中添加新元素的问题提交', 函数(e){}为了让您了解我想做的更多事情,我将此代码留在我的待办事项应用程序下面:

//The array im working with

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
}];

//looping to create new p elements on the html for todos

todos.forEach(function(todo){
let p = document.createElement('p');
p.textContent = todo.text;
document.querySelector('#todo').appendChild(p);
})

//the eventListener that i want to make add new .text property to the todo array inside a new object

document.querySelector('#form').addEventListener('submit', function(e){
e.preventDefault();
todos.push(e.target.elements.firstName.value)

最佳答案

由于您有一个包含“text”和“completed”属性的对象数组,因此您需要将具有该结构的新对象推送到数组中。

const newObject = {text: e.target.elements.firstName.value, completed: false};
todos.push(newObject);

或者如果你想压缩一下:

todos.push({text: e.target.elements.firstName.value, completed: false});

关于javascript - 如何从提交事件处理程序向对象数组添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57796515/

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