用JavaScript创建一个待办事项列表|青训营

107 阅读1分钟

首先,我们需要一个基本的HTML结构,包含一个输入框用于输入待办事项,一个按钮用于添加事项,以及一个列表来显示待办事项的内容。

<!DOCTYPE html>
<html>
<head>
  <title>Todo List</title>
</head>
<body>
  <h1>Todo List</h1>
  <input type="text" id="todoInput" placeholder="Add a new task">
  <button id="addButton">Add</button>
  <ul id="todoList"></ul>

  <script src="app.js"></script>
</body>
</html>

接下来,我们将使用JavaScript来实现待办事项列表的功能。

首先,我们需要获取DOM元素:

const todoInput = document.getElementById('todoInput');
const addButton = document.getElementById('addButton');
const todoList = document.getElementById('todoList');

然后,我们可以创建一个空数组来存储待办事项:

const todos = [];

接下来,我们实现添加待办事项的功能。当用户点击“Add”按钮时,我们将获取输入框中的文本,并将其添加到待办事项数组中。

addButton.addEventListener('click', function() {
  const todoText = todoInput.value.trim();
  if (todoText !== '') {
    todos.push(todoText);
    renderTodoList();
    todoInput.value = '';
  }
});

接下来,我们实现渲染待办事项列表的功能。每当待办事项数组发生变化时,我们将重绘整个列表。

function renderTodoList() {
  todoList.innerHTML = '';
  todos.forEach(function(todo, index) {
    const listItem = document.createElement('li');
    listItem.textContent = todo;
    listItem.addEventListener('click', function() {
      toggleTodoStatus(index);
    });
    todoList.appendChild(listItem);
  });
}

最后,我们实现了标记完成(或取消完成)待办事项的功能。当用户点击待办事项时,我们将切换其状态并更新样式。

function toggleTodoStatus(index) {
  const listItem = todoList.childNodes[index];
  listItem.classList.toggle('completed');
}

现在,我们可以编写CSS样式来美化待办事项列表:

.completed {
  text-decoration: line-through;
  color: gray;
}

通过上述代码,我们实现了一个简单的待办事项列表功能。用户可以输入新的事项,点击“Add”按钮来添加事项,点击事项来标记完成或取消完成。整个列表会根据用户的操作进行更新和渲染。这个例子演示了如何使用JavaScript来实现一个功能,并通过与HTML和CSS的结合来展现出来。