作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
编码员您好,我正在尝试制作一个简单的 javascript todo 应用程序,并且已经设置了一些内容,但现在我陷入了“如何从 addEventListener('” 的对象 todos 数组中添加新元素的问题提交', 函数(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});
关于javascript - 如何从提交事件处理程序向对象数组添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57796515/
我是一名优秀的程序员,十分优秀!