一、事件委托有三种方法
<button onclock="alert("hello world")">点击</button>
btn.onclick = function(){...}
-
btn.addEventListener(
click,function(){})
这里主要讲第3种,前两种会存在代码重复,当有多个以上就会无法同时展示出来
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
li{border:1px solid}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<button class="btn1">添加</button>
<button class="btn2">删除</button>
</body>
</html>
var btn1 = document.querySelector('.btn1')
var btn2 = document.querySelector('.btn2')
var ul = document.querySelector('ul')
var lis = document.querySelectorAll('li')
var lisL = lis.length
var liContent = ["11","22","33","44","55"]
var index = 0
// 添加li
btn1.addEventListener('click',function(){
console.log(index)
if(index<liContent.length){
let li = document.createElement('li')
li.textContent = liContent[index]
ul.appendChild(li)
index+=1
}
else if(index ==liContent.length){
return index = 0
}
})
// 删除最后li
btn2.addEventListener('click',function(){
ul.removeChild(ul.lastChild)
})
// 监听每一个li,当点击其中的li,打印出里面的Text
ul.addEventListener('click',function(e){
console.log(e.target.innerHTML)
})
网友评论