首页 > 解决方案 > 如何从提交事件处理程序向对象数组添加新元素

问题描述

你好编码器我正在尝试制作一个简单的 javascript todo 应用程序,我已经设置了一些东西,但现在我卡在“如何向 todos 对象数组中添加一个新元素,addEventListener('submit', function(e){} 以使你了解我想要做的更多我将此代码留在我的 todo 应用程序下方:

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

标签: javascriptarraysdomsubmitaddeventlistener

解决方案


由于您有一个具有“文本”和“已完成”属性的对象数组,因此您需要将具有该结构的新对象推送到您的数组中。

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

或者如果你想稍微浓缩一下:

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

推荐阅读