[英]How to add new elements to the objects array from the submit event handler
Hello coder i was trying to make a simple javascript todo app and i've already setup some stuff but now im stuck at 'how can i add a new element to the todos array of objects from the addEventListener('submit', function(e){}
to make u understand what i wanna do more i leave this code down below of my todo app: 您好编码员,我正在尝试制作一个简单的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)
Since you have an array of objects with 'text' and 'completed' properties, you will need to push a new object with that structure onto your array. 由于您具有具有'text'和'completed'属性的对象数组,因此需要将具有该结构的新对象压入数组。
const newObject = {text: e.target.elements.firstName.value, completed: false};
todos.push(newObject);
or if you want to condense it a bit: 或者,如果您想浓缩一下:
todos.push({text: e.target.elements.firstName.value, completed: false});
Value to add 增值
let value = e.target.elements.firstName.value,
object = {'text': value, 'completed':true };
todos.push(object);
Create a function that adds a task given its parameters, which in your case would look like this: 创建一个添加给定任务参数的函数,您的情况如下所示:
function addTask(name, completed) {
let p = document.createElement('p');
p.textContent = name;
document.querySelector('#todo').appendChild(p);
}
If you ever need to change the implementation, it will be well-contained in this function. 如果您需要更改实现,它将很好地包含在此函数中。
Then, when you need to add a new task (in this case in the submit handler), you just have to call the function: 然后,当您需要添加新任务 (在这种情况下,在提交处理程序中)时,只需调用函数:
document.querySelector('#form').addEventListener('submit', function(e) {
var title = document.querySelector('input[type="text"]').value;
addTask(title, false);
});
Abstracting your objectives in functions gives you benefits, like a more organized code, so as a bonus, you can now simplify how you create the very first tasks: 将函数中的目标抽象化会给您带来好处,就像更有组织的代码一样,因此,作为奖励,您现在可以简化创建第一个任务的方式:
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.