javascript - 如何从对象数组中删除元素
问题描述
在我正在制作的待办事项应用程序中,我想通过单击一个按钮来删除已完成的任务。
这就是我的body
:
<div id="div-todo"></div>
<button id="hide-todo">Hide completed</button>
<script src="script.js"></script>
</body>
这是我的js代码:
const todos = [
{
text: 'Learn HTML',
completed: true
},{
text: 'Learn CSS',
completed: true
},{
text: 'Learn Javascript',
completed: false
},{
text: 'Learn Nodejs',
completed: false
},{
text: 'Learn SQL',
completed: false
}
]
// renderring and printing tasks
const renderTodo = function (todos) {
const incompletedTodo = todos.filter(function (todo) {
return !todo.completed
})
//printing the h2 tag that containe the number of incompleted task
const summery = document.createElement('h2')
summery.textContent = `You have ${incompletedTodo.length} todos left. `
document.querySelector('#div-todo').appendChild(summery)
//printting all of tasks
todos.forEach(function (todo) {
const p = document.createElement('p')
p.textContent = todo.text
document.querySelector('#div-todo').appendChild(p)
})
// button setting
document.querySelector('#hide-todo').addEventListener('click',function (e) {
const completedTodo = todos.filter(function (todo) {
return todo.completed
})
e.target.textContent = 'Completed task is hide'
console.log(completedTodo)
})
}
renderTodo(todos)
我想用一个按钮隐藏未完成的任务,我什至记录了completedTodo
变量,但我不知道如何删除它们(我是 JS 新手)。
解决方案
问题是你的todos数组中的对象和实际的 html 元素之间没有“真正的”联系。因此,尽管一项任务可能被标记为已完成,但您不知道哪个段落元素正在显示该任务。要建立连接,请获取包含所有段落的父元素的所有子元素(div-todo),检查它的文本是否与 todos 数组中的文本匹配,如果任务被标记为已完成,则最终删除整个段落元素。
document.querySelector('#hide-todo').addEventListener('click', function(e) {
const completedTodo = todos.filter(function(todo) {
return todo.completed
})
e.target.textContent = 'Completed task is hide'
var myChild = document.getElementById("div-todo").childNodes;
for (var a = 0; a < myChild.length; a++) {
for (var b = 0; b < completedTodo.length; b++) {
if (myChild[a].textContent == completedTodo[b].text) {
myChild[a].parentNode.removeChild(myChild[a]);
}
}
}
})
推荐阅读
- javascript - 使用不同的值多次打印当前页面
- matlab - 仍然不明白如何在最优问题中添加松弛变量
- dialogflow-es - 如何使用 DialogFlow 获取字母数字类型的实体
- edges - OSMnx 教程 8(波音)- 中心性
- visual-studio-code - 有没有办法将后退和前进菜单项添加为工具栏 Visual Studio Code 上的按钮?
- vue.js - 如何使用 vue-router 自动更改页面?
- javascript - 使用循环返回子集
- python-3.x - 如何在熊猫数据框中删除多个(〜5000)列?
- c++ - 如何以模式获取数组中的数据?
- git - 如何恢复由于不正确的.gitattributes而损坏的PNG文件?