如何修复TodoList开发中的'Uncaught TypeError: Cannot read properties of null (reading 'appendChild')'错误?
解决TodoList提交表单时的'Uncaught TypeError: Cannot read properties of null (reading 'appendChild')'错误
你遇到的错误根源有两处:
- 选择器不匹配:JavaScript中你用
document.querySelector("#task-list")试图通过ID选择任务列表容器,但HTML里对应的section标签只有class="task-list",未设置ID。这会导致list_el变量为null,调用appendChild时触发错误。 - 语法错误:JavaScript代码开头的
window.addEventListener前多了一个多余的the,导致整个事件绑定代码无法正确执行。
修正后的JavaScript代码
//Random Alert alert('Better get to it or moms going to be angry') //Real work below window.addEventListener('load', () => { const form = document.querySelector("#new-task-form"); const input = document.querySelector("#new-task-input"); // 将选择器改为类选择器,匹配HTML中的class属性 const list_el = document.querySelector(".task-list"); form.addEventListener('submit', (e) => { e.preventDefault(); const task = input.value; if (!task) { alert("Please add/fill out the task"); return; } const task_el = document.createElement("div"); task_el.classList.add("task"); const task_content_el = document.createElement("div"); task_content_el.classList.add("content"); task_content_el.innerText = task; task_el.appendChild(task_content_el); list_el.appendChild(task_el); // 可选:提交后清空输入框 input.value = ''; }) })
另一种修正方案(修改HTML使用ID选择器)
如果更倾向用ID选择器,可修改HTML的section标签:
<body> <header> <h1>ToDo list 2022(version 1)</h1> <form id="new-task-form"> <input type="text" id="new-task-input" placeholder="what's on your mind today?"> <input type="submit" id="new-task-submit" value="Add task"> </form> </header> <main> <!-- 给section添加id属性,匹配JS中的ID选择器 --> <section class="task-list" id="task-list"> <h2>Tasks</h2> </section> </main> </body>
两种方案选其一即可,同时确保去掉JS代码中多余的the,这样提交表单后任务就能正常添加到列表中。
内容的提问来源于stack exchange,提问作者Bread
相关产品推荐
相关产品推荐

