You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

待办事项列表页面无法正常添加/显示待办项的问题求助

待办事项列表页面无法正常添加/显示待办项的问题求助

我现在遇到了一个待办事项列表的功能问题:页面能正常渲染所有HTML元素,但点击「Add To Do」按钮后,新的待办项不会显示在页面上,而且本地存储里的待办项也没法渲染出来。我感觉代码逻辑是通的,但肯定哪里有疏漏,麻烦帮忙排查一下问题所在?

我的HTML代码:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>To-Do List</title>
        <link rel="stylesheet" href="styles.css">
        <script src="/todolist.js" defer></script>
    </head>
    <body>
        <a href="index.html">Homepage</a>
        
        <ul class="todo-list">
            <!-- List items will go here -->
        </ul>
        
        <input type="text" id="new-todo" placeholder="Add a new item">
        <button type="button" id="add-todo">Add To Do</button>
    </body>
</html>

对应的JavaScript代码:

// get list from local storage
const todos = JSON.parse(localStorage.getItem('todo-list')) || []

// create consts
const todoList = document.getElementById('todo-list')
const input = document.getElementById('new-todo')
const addButton = document.getElementById('add-todo')

// create/add list items
const renderTodos = () => {
    // clear li's before we recreate them
    todoList.innerHTML = ''
    // loop through list of items and create li elements
    todos.forEach(todo => {
        const li = document.createElement('li')
        li.textContent = todo.text
        li.className = 'todo'
        todoList.append(li)
    })
}

// button event listener
addButton.addEventListener('click', () => {
    if (input.value) {
        todos.push({ text: input.value, completed: false });
        localStorage.setItem('todo-list', JSON.stringify(todos));
        input.value = '';
        renderTodos();
    }
});
renderTodos()

问题排查与解决方案

你代码里的核心问题是元素选择器不匹配,导致后续的渲染逻辑完全无法执行:

在HTML中,你的待办列表容器是用class="todo-list"定义的,但在JavaScript里,你用了getElementById('todo-list')去获取这个元素——getElementById()只会查找带有id属性的元素,而你的<ul>只有class没有id,所以todoList变量会变成null。后面所有操作todoList的代码(比如todoList.innerHTML = ''todoList.append(li))都会静默失败(你可以按F12打开浏览器开发者工具的Console面板,会看到类似Cannot set property 'innerHTML' of null的错误提示)。

修复方案(二选一即可)

  1. 修改HTML,给列表容器加上id
    <ul>标签改成同时包含id和class,让JS的选择器能匹配到:
<ul id="todo-list" class="todo-list">
    <!-- List items will go here -->
</ul>
  1. 修改JS,用class选择器获取元素
    把JS里获取列表容器的代码改成通过class选择器查找:
const todoList = document.querySelector('.todo-list')

修复后,你再测试功能:点击添加按钮后,新的待办项应该会正常渲染到页面上,而且刷新页面后,本地存储里的待办项也能正确加载并展示。

另外建议你平时开发时养成打开浏览器开发者工具的习惯,Console面板会直接抛出错误提示,能快速定位这类基础问题。

备注:内容来源于stack exchange,提问作者STARRCADE97

火山引擎 最新活动