[英]A variable in an anonymous function under EventListener staying undefined despite being previously declared and then defined clearly
所以我只使用 HTML 和 JS 制作一个基本的待办事项列表,由于某种原因,当我 go 向列表中添加一个项目时,我用于 Z99938282F04071859941E18F16 的变量返回空元素在“清除”按钮的 EventListener 下执行 function 后“未定义”。 有人可以帮忙吗? HTML和JS附在下面:
let todos = []; let add = document.querySelector("#add"); let remove = document.querySelector("#remove") let clear = document.querySelector("#clear") let todolist = document.querySelector("#todolist") let addTodo; let clearedTodo; let newTodo; add.addEventListener("click", function() { addTodo = prompt("Enter the item you would like to add.") todos.push(addTodo); todolist.innerHTML += "<li></li>" newTodo = document.getElementsByTagName("li")[todos.length - 1] newTodo.textContent = addTodo; }) remove.addEventListener("click", function() { let removeTodo = prompt("Enter the index number of the item you would like to remove.") - 1; let removedTodo = document.getElementsByTagName("li")[removeTodo] removedTodo.remove(); todos.splice(removeTodo, 1); }) clear.addEventListener("click", function() { todos = []; document.querySelector("ol").remove(); document.querySelector("div").innerHTML += '<ol id="todolist"></ol>' console.log("To Do list was cleared.") })
<h1>The Ultimate To Do List</h1> <p>Click on an item to mark as done.</p> <button id="add">ADD</button> <button id="remove">REMOVE</button> <button id="clear">CLEAR</button> <div id="clearer"> <ol id="todolist"> </ol> </div>
谢谢。
问题出在你清楚的 function 中。 大多数情况下,它看起来不错,除了一个导致重大错误的问题。 当您删除所有“ol”元素时,您的todolist
var 将失去引用,因为它没有任何可指向的内容。 你必须重新声明它。
但是有一种更简单的方法可以解决这个问题。 删除这些行:
document.querySelector("ol").remove();
document.querySelector("div").innerHTML += '<ol id="todolist"></ol>'
请改用此行:
todolist.innerHTML = "";
现在 DOM 中的 todo 列表也被清除了,你的todolist
仍然指向它应该指向的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.