大家好,我制作了一个待办事项应用程序,可以接收用户的输入并使其成为待办事项,并且我还添加了一个过滤框,但由于某些原因它似乎不起作用(它在拆分代码之前曾经起作用进入函数调用和基本代码,以便即时通讯将整个代码放到这里,希望您能理解代码。 编辑:过滤返回待办事项,包括在过滤输入框中的文本。
函数调用部分:
//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>
答案 0 :(得分:1)
更改
filteredTodo = todos.filter(function(todo){
return !filters.hideCompleted || !todo.completed;
})
到
filteredTodo = filteredTodo.filter(function(todo){
return !filters.hideCompleted || !todo.completed;
})
否则,您将取消原始过滤。