事件代理的应用
2019-02-21 本文已影响0人
学的会的前端
事件代理
原理:利用事件冒泡,把事件监听绑定到其父容器上。
应用场景:页面上有新增的元素,新增的元素也需要绑定事件。
源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件</title>
<style>
.container {
margin: 30px auto;
width: 900px;
}
ul,li {
margin: 0;
padding: 0;
list-style: none;
}
.container li {
border: 1px solid #ccc;
line-height: 1.5;
}
#show {
background: #ccc;
}
#btn {
border-radius: 3px;
outline: none;
margin: 3px 0;
display: inline-block;
}
</style>
</head>
<body>
<div class = "container">
<ul>
<li>aa</li>
<li>bb</li>
<li>cc</li>
<li>dd</li>
</ul>
<input id = "add-ipt" type = "text"><button id = "btn">添加</button>
<div id = "show"></div>
</div>
<script>
var liNodes = document.querySelectorAll('.container li')
var showNode = document.querySelector('#show')
var addNode = document.querySelector('#btn')
var addIpt = document.querySelector("#add-ipt")
var container = document.querySelector('.container ul')
liNodes.forEach(function(node){ //传入参数
node.addEventListener('click',function(){
showNode.innerText = this.innerText
})
})
addNode.addEventListener('click',function(){
var node = document.createElement('li')
node.innerText = addIpt.value
node.addEventListener('click',function(){
showNode.innerText = this.innerText
})
container.appendChild(node)
})
</script>
</body>
</html>
事件代理的改进方法
container.addEventListener('click',function(e){
var target = e.target
if(target.tagName.toLowerCase() === 'li')
showNode.innerText = target.innerText
})
addNode.addEventListener('click',function(){
var node = document.createElement('li')
node.innerText = addIpt.value
container.appendChild(node)
//新增元素不需要在绑定事件
})
要求:当鼠标放置在li元素上,会在img-preview里展示当前li元素的data-img对应的图片。
<ul class="ct">
<li data-img="http://cdn.jirengu.com/book.jirengu.com/img/11.jpg">鼠标放置查看图片1</li>
<li data-img="http://cdn.jirengu.com/book.jirengu.com/img/13.jpg">鼠标放置查看图片2</li>
<li data-img="http://cdn.jirengu.com/book.jirengu.com/img/14.jpg">鼠标放置查看图片3</li>
</ul>
<div class="img-preview"></div>
<script>
var ct = document.querySelector('.ct'),
childs = ct.querySelectorAll('li'),
preview = document.querySelector('.img-preview');
for(var i=0; i<childs.length; i++){
childs[i].addEventListener('mouseenter', function(){
var dataImg = this.getAttribute('data-img');
preview.innerHTML = '<img src="' + dataImg + '">'
});
}