猿问

由于某种原因,使用过滤器过滤对象数组不起作用

大家好,我制作了一个 todo 应用程序,它接受用户的输入并使它们成为 todos,我还添加了一个过滤框,但由于某种原因它似乎不起作用(它曾经在将代码拆分为函数调用之前起作用)和基本代码,所以我要把整个代码放在这里,我希望你理解代码。编辑:过滤返回包含过滤输入框中文本的待办事项。


函数调用部分:


//Read and parse existing data in local storage

const getSavedTodos = function() {

    const todoJSON = localStorage.getItem('todo');


    if (todoJSON !== null) {

    return JSON.parse(todoJSON)

    } else {

        return []

    }

}


// save the todos in locale storage

const saveTodos = function(todos) {

    localStorage.setItem('todo', JSON.stringify(todos))

}


// Render todos 

let renderTodos = function(todo, filters) {

    let filteredTodo = todo.filter(function(todo){

        return todo.text.toLowerCase().includes(filters.text.toLowerCase());

    })


    filteredTodo = todos.filter(function(todo){

        return !filters.hideCompleted || !todo.completed;

    })


    document.querySelector('#todo').innerHTML = '';


    const incompleteTodos = filteredTodo.filter(function (todos) {

        return !todos.completed

    })



    const summary = document.createElement('h2')

    summary.textContent = `You have ${incompleteTodos.length} todos left`

    document.querySelector('#todo').appendChild(summary)


    filteredTodo.forEach(function(todo){

        let p = document.createElement('p');

        p.textContent = todo.text;

        document.querySelector('#todo').appendChild(p);

    })

}

基本代码部分:


let todos = getSavedTodos();




let filters = {

    text: '',

    hideCompleted: false

}


renderTodos(todos, filters);


document.querySelector('#filter').addEventListener('input', function(e){

    filters.text = e.target.value.toLowerCase();

    renderTodos(todos, filters);

})



慕仙森
浏览 168回答 1
1回答

开心每一天1111

改变filteredTodo = todos.filter(function(todo){    return !filters.hideCompleted || !todo.completed;})到filteredTodo = filteredTodo.filter(function(todo){    return !filters.hideCompleted || !todo.completed;})否则,您将废弃原始过滤器。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答