待办事项工具js代码
时间: 2023-11-21 22:57:45 浏览: 48
以下是一个简单的待办事项工具的JavaScript代码示例:
```javascript
// 获取待办事项列表元素
const todoList = document.getElementById('todo-list');
// 获取添加待办事项表单元素
const todoForm = document.getElementById('todo-form');
// 待办事项数组
let todos = [];
// 添加待办事项函数
function addTodo() {
// 获取输入框的值
const todoInput = document.getElementById('todo-input');
const todoText = todoInput.value.trim();
// 如果输入框为空,则不添加待办事项
if (!todoText) {
return;
}
// 创建待办事项对象
const todo = {
id: Date.now(),
text: todoText,
completed: false
};
// 将待办事项添加到数组中
todos.push(todo);
// 渲染待办事项列表
renderTodoList();
// 清空输入框
todoInput.value = '';
}
// 渲染待办事项列表函数
function renderTodoList() {
// 清空待办事项列表
todoList.innerHTML = '';
// 遍历待办事项数组,创建待办事项元素并添加到列表中
todos.forEach(todo => {
const todoItem = document.createElement('li');
todoItem.innerHTML = `
<input type="checkbox" ${todo.completed ? 'checked' : ''} onchange="toggleTodoCompleted(${todo.id})">
<span>${todo.text}</span>
<button onclick="removeTodoItem(${todo.id})">删除</button>
`;
todoList.appendChild(todoItem);
});
}
// 切换待办事项完成状态函数
function toggleTodoCompleted(id) {
// 查找待办事项对象
const todo = todos.find(todo => todo.id === id);
// 切换完成状态
todo.completed = !todo.completed;
// 渲染待办事项列表
renderTodoList();
}
// 删除待办事项函数
function removeTodoItem(id) {
// 查找待办事项对象的索引
const index = todos.findIndex(todo => todo.id === id);
// 删除待办事项对象
todos.splice(index, 1);
// 渲染待办事项列表
renderTodoList();
}
// 添加待办事项表单提交事件
todoForm.addEventListener('submit', event => {
event.preventDefault();
addTodo();
});
// 初始化待办事项列表
renderTodoList();
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)