待办列表项点击添加删除线功能报错Uncaught TypeError求助
Hey there! Let's figure out why you're getting that Uncaught TypeError and fix your to-do list strike-through feature.
The problem here is that document.getElementsByTagName("li") doesn't return a single DOM element—it gives you an HTMLCollection, which is an array-like object of all the <li> elements on the page. HTMLCollections don't have an addEventListener method (or a classList property) directly attached to them, hence the error when you try to call those methods on togList.
Solution 1: Bind the event to each <li> individually
You can loop through the HTMLCollection and attach the click event to every <li> element one by one:
var togList = document.getElementsByTagName("li"); function togglesOnOff() { // Use `this` to reference the specific <li> that was clicked this.classList.toggle("done"); } // Loop through each <li> and add the event listener for (var i = 0; i < togList.length; i++) { togList[i].addEventListener("click", togglesOnOff); }
Just make sure you have the corresponding CSS for the done class to show the strike-through:
.done { text-decoration: line-through; }
Solution 2: Use Event Delegation (Better for Dynamic Lists)
If you plan on adding new to-do items dynamically later, event delegation is a smarter approach. Instead of binding events to each <li>, you bind a single event to their parent container (usually a <ul>), and use event bubbling to handle clicks on child <li>s:
// Grab the parent <ul> container var todoListContainer = document.querySelector("ul"); function togglesOnOff(e) { // Make sure we're only reacting to clicks on <li> elements if (e.target.tagName === "LI") { e.target.classList.toggle("done"); } } // Attach the event listener to the parent container todoListContainer.addEventListener("click", togglesOnOff);
This way, any new <li>s you add to the list later will automatically have the click functionality without needing to re-run your event binding code.
内容的提问来源于stack exchange,提问作者izee

