javascript - 如何使用事件侦听器向对象数组添加新元素并将其显示在 html 页面上(编辑代码)
问题描述
(我之前发布过这个问题,但是我忘记添加一个缺失的元素,所以人们认为这是问题所在,但实际上并非如此,所以我再次使用我应该首先使用的正确代码再次发布)
我正在尝试制作一个todo 应用程序,然后我想使用 aform
和 an添加新的 todoevent listener
但是,当我完成代码时,该应用程序仅将书面文本添加到 中object-array
,而实际上并没有将其添加到 html 中的 todos 列表中页。
我将在下面提供一个小代码,显示数组、设置代码和 html,以使这个问题简短,但如果你想查看整个应用程序代码,请随时查看这个 github 的存储库:https:/ /github.com/salahmak/Todo-application
您还可以从此ngrok
链接查看应用程序的实时版本(我会一直保持它直到我解决问题):http: //7eb95c9a.ngrok.io
编码:
// The array
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
}];
//creating p elements and assigning their text content to each "text" property of the "todos" array
todos.forEach(function(todo) {
let p = document.createElement('p');
p.textContent = todo.text;
document.querySelector('#todo').appendChild(p);
})
<h1>Todos</h1>
<div id="todo"></div>
<form id="form">
Add a new todo
<input type="text" placeholder="Type your first name" name="firstName">
<button>Submit</button>
</form>
解决方案
试试这个(添加元素后更新 DOM):
document.querySelector('#form').addEventListener('submit', function(e) {
e.preventDefault();
let newObject = { text: e.target.elements.firstName.value, completed: false };
todos.push(newObject);
renderTodos(todos, filters);
});
这是完整的小提琴示例: https ://jsfiddle.net/9j2nky6q/
推荐阅读
- c# - 查找字体风格/样式是否在单独的文件中或由 Windows 生成
- python - 日期时间、时间增量和单独的线图、绘图区域
- unity3d - Blender 到 Unity 的奇怪转换
- java - SoapUI Loop through TestCases and log test case custom property
- javascript - Why the array returning empty spaces
- ios - How to add pagination in UICollectionView in swift?
- python - sorted not taking lambda returning tuple as key argument
- c - 如何将单词保存到动态列表中
- android - 如何从给定结构中搜索firebase android中的数据
- android - 我的 API 没有显示任何内容并且没有错误?