07-JavaScrpit-事件
DOM事件介绍
- 点击一个DOM元素
- 键盘按一下一个键
- 输入框输入内容
- 页面加载完成
编写一个通用的事件监听函数
描述事件冒泡流程
对于一个无限下拉加载图片的页面,如何给每个图片绑定事件
通用事件绑定
var btn = document.getElementById('btn1');
btn.addEventListener('click',function (event) {
console.log('clicked');
})
function bindEvent(elem,type,fn) {
elem.addEventListener(type,fn);
}
var a = document.getElementById('link1')
bindEvent(a,'click',function(e){
e.preventDefault();
alert('clicked');
});
事件冒泡
<body>
<div id="div1">
<p id="p1">激活</p>
<p id="p2">取消</p>
<p id="p3">取消</p>
<p id="p4">取消</p>
</div>
<div id="div2">
<p id="p5">取消</p>
<p id="p6">取消</p>
</div>
</body>
var p1 = document.getElementById('p1');
var body = document.body;
bindEvent(p1,'click',function (e) {
e.stopPropatation();
alert('激活');
});
bindEvent(body,'click',function(e){
alert('取消');
})
代理
<div id="div1">
<a href="#">a1</a>
<a href="#">a2</a>
<a href="#">a3</a>
<a href="#">a4</a>
</div>
var div1 = document.getElementById('div1');
div1.addEventListener('click',function (e) {
var target = e.target;
if (target.nodeName === 'A') {
alert(target.innerHTML);
}
})
完善通用绑定事件的函数
var div1 = document.getElementById('div1');
bindEvent(div1,'click','a',function (e) {
console.log(this.innerHTML);
})
function bindEvent(elem,type,selector,fn) {
if (fn == null) {
fn = selector;
}
elem.addEventListener(type,function (e) {
var target;
if (selector) {
target = e.target;
if (target.matches(selector)) {
fn.call(target,e);
}
}else {
fn(e);
}
})
}