簡體   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