Todo列表中点击<li>元素无法添加CSS类的问题求助
Hey there! Let's get that click-to-mark-task-done feature working for you. I found a couple of key issues in your JavaScript code that are preventing the done class from applying when you click list items:
1. You're only selecting the first list item
Your line var items = ul.getElementsByTagName("li")[0]; adds [0], which grabs only the first <li> element instead of all list items. This means:
- Only the first list item gets a click event listener
- The
forloop intaskDone()won't run (since a single element doesn't have alengthproperty)
2. Dynamic list items don't get click listeners
Even if you fixed the selection issue, any new <li> elements you create with createListElement() won't have click event listeners attached—your original code only binds listeners to items that exist when the page loads.
The Best Fix: Use Event Delegation
Instead of attaching listeners to each individual <li>, we can bind a single listener to the parent <ul> element. This works because click events "bubble up" to parent elements, and we can check if the clicked element was a list item.
Here's the revised JavaScript code with fixes applied:
var button = document.getElementById('button'); var input = document.getElementById('userinput'); var ul = document.getElementById("foo"); function inputLength(){ return input.value.length > 0; } function createListElement(){ var li = document.createElement("li"); li.appendChild(document.createTextNode(input.value)); ul.appendChild(li); input.value = ""; } function addListAfterClick(){ if (inputLength()) { createListElement(); } } function addListAfterKeyPress(event){ // Added event parameter to avoid relying on global event variable if (inputLength() && event.keyCode === 13) { createListElement(); } } function taskDone(event){ // Check if the clicked element is an LI before toggling the class if(event.target.tagName === "LI"){ event.target.classList.toggle("done"); } } // Bind click listener to the UL instead of individual LIs ul.addEventListener("click", taskDone); button.addEventListener("click", addListAfterClick); input.addEventListener("keypress", addListAfterKeyPress);
Key Changes Explained:
- Removed the
itemsvariable and individual<li>listener setup - Added a click listener to the parent
<ul>element - In
taskDone(), we useevent.targetto get the actual clicked element, then check if it's an<li>before toggling thedoneclass - Fixed
addListAfterKeyPress()to accept theeventparameter (avoids issues with globaleventin strict mode)
This approach works for both existing and dynamically added list items, and keeps your code cleaner. Your CSS and HTML are already good to go—with this JS update, clicking any list item will toggle the strikethrough style!
内容的提问来源于stack exchange,提问作者Ruby prO

