gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:53:06 25 4
gpt4 key购买 nike

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

函数调用部分:

//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);
})

document.querySelector('#form').addEventListener('submit', function(e){
e.preventDefault();
todos.push({
text: e.target.elements.firstName.value,
completed: false
})
saveTodos(todos);
renderTodos(todos, filters);
e.target.elements.firstName.value = '';
})

document.querySelector('#hide-completed').addEventListener('change', function(e){
filters.hideCompleted = e.target.checked;
renderTodos(todos, filters);
})

HTML部分:

<header class="header">
<h1>Todos application</h1>
</header>

<input type="text" id="filter" placeholder="filter the todos">
<label class="checkbox">
<input type="checkbox" id="hide-completed">
<span>hide completed todos</span>
</label>
<div id="todo"></div>
<hr>
<form id="form">
Add a new todo:
<input type="text" placeholder="Type your first name" name="firstName" class="inpt">
<input type="submit" value="submit" class="btn">
</form>

<script src="refraction.js"></script>
<script src="todo-app.js"></script>

最佳答案

改变

filteredTodo = todos.filter(function(todo){
return !filters.hideCompleted || !todo.completed;
})

filteredTodo = filteredTodo.filter(function(todo){
return !filters.hideCompleted || !todo.completed;
})

否则你就废弃了原来的过滤。

关于javascript - 由于某种原因,使用过滤器过滤对象数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58106339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com