在此,我想删除具有特定删除按钮的孩子。但是当我运行此代码时,它将只删除我在输入中插入的一个活动。
function addItemTodo(text){
list = document.getElementById("todo");
item = document.createElement('li');
item.innerText = text;
trash = document.createElement('button');
trash.classList.add('btn1');
trash.addEventListener("click", removeActivity);
icon_trash = document.createElement('i');
icon_trash.classList.add('fas','fa-trash-alt','fa-2x');
check = document.createElement('button');
check.classList.add('btn2');
icon_check = document.createElement('i');
icon_check.classList.add('fas','fa-check','fa-2x');
item.appendChild(trash);
trash.appendChild(icon_trash);
item.appendChild(check);
check.appendChild(icon_check);
list.appendChild(item);
}
//if user click on the button, remove the activity from the list of Activity
function removeActivity(){
list.removeChild(item);
console.log("item removed!");
}
答案 0 :(得分:0)
将函数removeActivity()更改为以下代码
function removeActivity(){
var listItems = document.getElementsByTagName("li");
for (var i = 0; i < listItems.length; i++) {
listItems[i].onclick = function() {
this.parentNode.removeChild(this);
}
}
}