javascript - 如何从提交事件处理程序向对象数组添加新元素
问题描述
你好编码器我正在尝试制作一个简单的 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)
解决方案
由于您有一个具有“文本”和“已完成”属性的对象数组,因此您需要将具有该结构的新对象推送到您的数组中。
const newObject = {text: e.target.elements.firstName.value, completed: false};
todos.push(newObject);
或者如果你想稍微浓缩一下:
todos.push({text: e.target.elements.firstName.value, completed: false});
推荐阅读
- mysql - RMySQL - 自动从数据库表中读取数据
- r - 正则表达式:匹配同一字符串的部分但不包括特定部分
- sql-server - 处理来自存储过程的数据返回多个表
- java - 我的应用程序图标未在某些设备上显示 - 为什么?
- python - 如何将数组转换为模型输入?
- postgresql - 单元测试代码:= 运行时错误:无效的内存地址或 nil 指针取消引用
- java - 如何在事务开始之前或提交之前执行操作?
- java - 在设备上或从底栏按下返回按钮时,不会调用 onBackPressed
- sql - 如何在 SQL 的列中随机分配一组值?
- php - 如何显示 PHP 内部 web 服务器的介绍文本