首页 > 解决方案 > 如何从对象数组中删除元素

问题描述

在我正在制作的待办事项应用程序中,我想通过单击一个按钮来删除已完成的任务。

这就是我的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 新手)。

标签: javascript

解决方案


问题是你的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]);
        }
      }
    }
  })

推荐阅读