我正在尝试通过单击待办事项列表项上的删除按钮来删除该项。我不确定如何准确地做到这一点。
添加项目的代码有效,但是删除按钮功能无效。
document.getElementById('button').addEventListener('click',function addTodo(){ var value = document.getElementById('input').value; const item = `<li> <div class="item"> <div class="complete"> <button id="complete" class="todo">Complete</button> </div> <p class="text">${value}</p> <div class="remove"> <button id="remove" class="todo">Remove</button> </div> </div> </li>`; const position = "beforeend"; list.insertAdjacentHTML(position,item); }); document.getElementById('remove').addEventListener('click',function removeTodo(){ var item = this.closest( 'li' ); item.remove(); });
<div class="container"> <header> <input type="text" id="input" placeholder="Add an item"/> <button id="button" type="button">Add item </button> </header> <div id="list"></div> </div>
[当我检查控制台时,出现“ TypeError:document.getElementById(...)为空app.js:24:10”]
我正在尝试通过单击待办事项列表项上的删除按钮来删除该项。我不确定如何准确地做到这一点。添加项目的代码有效,但是删除按钮功能...
问题是您的代码试图将事件附加到不存在的元素上。将新项目添加到列表后,您就想参加该活动。
您正在尝试生成具有相同ID的多个html对象。这就是为什么这不起作用。当您的JavaScript查找ID为“ remove”的元素时,它将找到其中的几个,这是永远不会发生的。另外,还要注意id =“ complete”。每次添加新的待办事项时,尝试增加ID。