为新添加的新元素绑定新事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<select name="" id="new-el-position">
<option value="front">在按钮前方插入</option>
<option value="behind">在按钮后方插入</option>
</select>
<br>
<div id="container">
<button id="add-new-el">添加新元素~</button>
<br>
<button id="add-new-ev">为其绑定事件~</button>
</div>
</body>
<script>
var addNewEl = document.getElementById("add-new-el"),
addNewEvent = document.getElementById("add-new-ev"),
container = document.getElementById("container"),
selectPos = document.querySelector("select");
// var newEl = "<p>一个新的弟弟元素</p>";//错误写法,insertBefore中插入的节点必须是Node
var newEl = document.createElement("p");
var newElText = document.createTextNode("这是一个新的弟弟元素");
newEl.setAttribute("class","newEl");
newEl.append(newElText);
addNewEl.onclick = function(){
if(selectPos.value == "front"){
container.insertBefore(newEl,addNewEl);
}else{
container.insertBefore(newEl,addNewEl.nextSibling);
}
}
addNewEvent.onclick = function(){
console.log(document.getElementsByClassName("newEl").length);
if(document.getElementsByClassName("newEl").length != 0){
document.getElementsByClassName("newEl")[0].addEventListener('click',function(){
alert("事件已绑定");
})
}else{
alert("元素未创建");
}
}
</script>
</html>