1、通用事件封装及代理
当动态数据很多时,如何给每个img绑定点击事件-代理;
代理的好处:
- 代码简洁,只会对父级dom做一次的事件绑定
- 给浏览器的压力也比较小(内存或渲染的压力)
事件冒泡过程:
- 根据dom树形结构一层一层向上冒泡;(阻止冒泡)
<div id="div1"> div1</div>
<div id="div2"> div2</div>
<div id="div3"> div3</div>
<div class="link" id="link">
<img src="image/1.jpg" alt="">
<img src="image/2.jpg" alt="">
<img src="image/1.jpg" alt="">
<div>divlink</div>
</div>
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var link = document.getElementById('link');
bindEvent(app,'click',function (e) {
// e.stopPropagation();//取消事件冒泡
alert('通用事件监听app');
});
bindEvent(div1,'click',function (e) {
e.stopPropagation();//取消事件冒泡
alert('通用事件监听1');
});
bindEvent(div2,'click',function (e) {
e.stopPropagation();//取消事件冒泡
alert('通用事件监听2');
});
bindEvent(div3,'click',function (e) {
e.stopPropagation();//取消事件冒泡
alert('通用事件监听3');
});
bindEvent(link,'click','img',function (e) {
e.stopPropagation();
alert('img')
});
function bindEvent(ele,type,selector,fun) {
if (!fun){
fun = selector;
selector = null;
}
ele.addEventListener(type,function (e) {
if (selector){
var taget = e.target;
console.log(taget);
if (taget.matches(selector)){
fun.call(taget,e);
}
//代理
}else {
//无代理
fun(e)
}
});
}