繁体   English   中英

如何通过提交事件处理程序将新元素添加到对象数组

[英]How to add new elements to the objects array from the submit event handler

您好编码员,我正在尝试制作一个简单的javascript todo应用程序,并且我已经设置了一些东西,但是现在我陷入了“如何从addEventListener('submit', function(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});

增值

let value = e.target.elements.firstName.value,
object = {'text': value, 'completed':true }; 

todos.push(object);

创建一个添加给定任务参数的函数,您的情况如下所示:

function addTask(name, completed) {
    let p = document.createElement('p');
    p.textContent = name;
    document.querySelector('#todo').appendChild(p);
}

如果您需要更改实现,它将很好地包含在此函数中。

然后,当您需要添加新任务 (在这种情况下,在提交处理程序中)时,只需调用函数:

document.querySelector('#form').addEventListener('submit', function(e) {
    var title = document.querySelector('input[type="text"]').value;
    addTask(title, false);
});

将函数中的目标抽象化会给您带来好处,就像更有组织的代码一样,因此,作为奖励,您现在可以简化创建第一个任务的方式:

const todos = [{
    text: 'wake up',
    completed: true
}, {
    text: 'get some food',
    completed: true
}];

todos.forEach(function(todo) {
    addTask(todo.text);
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM