事件绑定函数(完善)
function bindEvent(elem,type,selector,fn) {
if(fn == null){
fn = selector;
selector = null;
}
elem.addEventListener(type,function(e){
if(selector){
const target= e.target
if(target.matches(seletor)){
fn.call(target, e)
}
}else {
fn(e);
}
});
}
代码如下
事件冒泡
<body>
<div>
<p id ="p1">激活</p>
<p id ="p2">取消</p>
<p id ="p3">取消</p>
</div>
<div>
<p id ="p4">取消</p>
<p id ="p5">取消</p>
</div>
</body>
let body =document.body
let p1 =document.getElementById('p1');
bindEvent(p1,'click',function(e){
e.stopPropagation(); //阻止事件冒泡
alert('激活')
})
bindEvent(body,'click',function(e){
alert('取消')
})
另外
使用bind绑定的事件,用unbind解除绑定
使用delegate绑定的事件,用undelegate解除绑定
使用on绑定的事件,用off解除绑定
通用事件绑定
function bindEvent(elem,type,fn) {
elem.addEventListener(type,fn);
}
let a =document.getElementById('a');
bindEvent(a,'click',function(e){
e.preventDefault() //阻止浏览器默认行为,防止调转
alert(‘clicked’);
})
本文章来给大家介绍一下关于jQuery中live绑定的事件与解除绑定两个方法,希望此文章对各位同学会有所帮助。
事件代理
<body>
<div id="div1">
<p id ="p1">激活</p>
<p id ="p2">取消</p>
<p id ="p3">确认</p>
</div>
</body>
let body =document.body
let div1 =document.getElementById('div1');
bindEvent(div1,'click',function(e){
const target =e.target;
if(target.nodeName === 'A') { //判断是否是a标签
alert('target.innerHTML')
}
})
复制代码
解决:使用unbind("click")方法先解除绑定的事件再绑定新事件,即在给对象绑定事件之前先移除该对象上的原有事件
二,解除live绑定的事件
//先通过die()方法解除,再通过live()绑定
$("#selectAll").die().live("click",function(){
//事件运行代码
});
代码如下
本文由wns9778.com发布于计算机教程,转载请注明出处:wns9778.comJS基础——事件操作总结
关键词: wns9778.com