js事件

来源:互联网 发布:ca检测网络检测未通过 编辑:程序博客网 时间:2024/06/08 02:01

一、通用事件绑定

function bindEvent(elem,type,fn){  elem.addEventListener(type,fn);}var a=document.getElementById('link1');bindEvent(a,'click',function(e){  e.preventDefault();  //阻止默认行为  alert('clicked');})

IE低版本使用attachEvent绑定事件,和W3C标准不一样

二、事件冒泡

事件冒泡思想:从目标元素往上不断冒泡触发父元素事件最终可以冒泡到window上
阻止事件冒泡:e.stopPropagation();
阻止默认行为:e.preventDefault();
事件捕获思想:不太具体的节点先触发事件,然后逐级向下触发目标元素事件
阻止事件捕获: e.stopPropagation()方法既可以阻止事件冒泡,也可以阻止事件捕获,也可以阻止处于目标阶段;
e.stopImmediatePropagation()方法也可阻止事件捕获和阻止事件冒泡
e.stopImmediatePropagation()e.stopPropagation()的区别:后者只会阻止冒泡或者是捕获。 但是前者除此之外还会阻止该元素的其他事件发生,但是后者就不会阻止其他事件的发生

事件代理:

<div id="div1">  <a herf="#">a1</a>  <a herf="#">a2</a>  <a herf="#">a3</a>  <a herf="#">a4</a>  <!--会随时新增a标签--></div>var div1 = document.getElementById('div1');div1.addEventListener('click',function(e){  var target = e.target;  if(target.nodeName ==='A'){    alert(target.innerHTML);  }})

三、完善通用绑定事件函数

function bindEvent(elem,type,selector,fn){ if(fn==null){  fn=selector;  selector=null; } elem.arrEventListener(type,function(e){  var target;  if(slector){   target=e.target;   if(target.matches(selector){    fn.call(target,e);   }  }else{   fn(e);  } })}//使用代理var div1 = document.getElementById('div1');bindEvent(div1,'click','a',function(e){  console.log(this.innerHTML);})//不使用代理var a = document.getElementById('a1');bindEvent(div1,'click',function(e){  console.log(a.innerHTML);})

代理好处:减少浏览器内存占用,代码简洁