2 回答
TA贡献1877条经验 获得超1个赞
你很接近,你只需要做一些改变就可以让它工作:
添加deleteTaskButton作为列表项的子项newTask。您将其添加为同级元素,但如果我们将其设为子元素,则会将其直接与元素相关联li,因此我们可以轻松找到li您要删除的元素:
function taskList() {
[...]
document.getElementById("taskLister").appendChild(newTask);
newTask.appendChild(deleteTaskButton); // 1. add to the new task li
[...]
}
现在在您的removeTask函数中,传入的单击按钮是li您选择删除的按钮的子元素,因此您只需要获取其父元素并将其删除:
function removeTask(i) {
let deleteTask = i.target.parentElement;
deleteTask.remove();
}
这就是您所需要的!
TA贡献1876条经验 获得超6个赞
工作示例:
let button = document.getElementById("taskButton");
button.addEventListener('click', () => taskList());
function taskList() {
let item = document.getElementById("taskInput").value;
let newTask = document.createElement("li");
let deleteTaskButton = document.createElement("button");
deleteTaskButton.textContent = "Delete "+item;
newTask.innerText = item;
document.getElementById("taskLister").appendChild(newTask);
newTask.appendChild(deleteTaskButton); /* 1. ADD BUTTON TO LI */
if (markTaskComplete) {
newTask.addEventListener('click', (e) => markTaskComplete(e));
deleteTaskButton.addEventListener('click', (i) => removeTask(i));
}
}
function markTaskComplete(e) {
let strikeThrough = e.target;
strikeThrough.style.textDecoration = "line-through";
}
function removeTask(i) {
/* 2. THE BUTTON IS NOW A CHILD OF THE LI, SO DELETE ITS PARENT */
let deleteTask = i.target.parentElement;
deleteTask.remove();
}
<div class="container">
<h1>TO DO LIST</h1>
<form id="taskForm">
<input id="taskInput"></input>
<button type="button" id="taskButton">Click Here</button>
</form>
<ul id="taskLister"></ul>
</div>
另外仅供参考,要将文本添加到按钮,您可以使用textContent而不是innertext,例如
deleteTaskButton.textContent = "Delete "+item;
添加回答
举报