1.给按钮分别绑定点击事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul id="list">
</ul>
<script>
var arr = ["111","222","333"]
for(var i=0;i<arr.length;i++){
var oli = document.createElement("li")
oli.innerHTML = arr[i]
var obutton = document.createElement("button")
obutton.innerHTML = "Delete"
obutton.onclick = handler
oli.appendChild(obutton)
list.appendChild(oli)
}
function handler(){
// console.log(1111)
// 找到父节点删除自身并删除后代
this.parentNode.remove()
}
</script>
</body>
</html>
2.优化:利用冒泡机制直接给列表ul绑定点击事件,再根据target获取事件源
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul id="list">
</ul>
<script>
var arr = ["111","222","333"]
for(var i=0;i<arr.length;i++){
var oli = document.createElement("li")
oli.innerHTML = arr[i]
var obutton = document.createElement("button")
obutton.innerHTML = "Delete"
oli.appendChild(obutton)
list.appendChild(oli)
}
list.onclick = function(event){
console.log(event.target.nodeName)
if(event.target.nodeName==="BUTTON"){
event.target.parentNode.remove()
}
}
</script>
</body>
</html>
效果显示: