js事件委托机制

来源:互联网 发布:机顶盒的电视直播软件 编辑:程序博客网 时间:2024/05/22 04:31

1,什么是事件委托:通俗的讲,事件就是onclick,onmouseover,onmouseout,等就是事件,委托呢,就是让别人来做,这个事件本来是加在某些元素上的,然而你却加到别人身上来做,完成这个事件。

也就是:利用冒泡的原理,把事件加到父级上,触发执行效果。

好处呢:1,提高性能。

我们可以看一个例子:需要触发每个li来改变他们的背景颜色。


<html><head></head><body><ul id="ul"><li>aaa</li><li>bbb</li><li>ccc</li></ul></body><script>window.onload=function(){var aUL=document.getElementById("ul");var aLI=aUL.getElementsByTagName("li");   for(var i=0;i<aLI.length;i++){    aLI[i].onmouseover=function(){this.style.background="red";}   aLI[i].onmouseout=function(){this.style.background="";}    }  }</script></html>

 这样我们就可以做到li上面添加鼠标事件。

但是如果说我们可能有很多个li用for循环的话就比较影响性能。

下面我们可以用事件委托的方式来实现这样的效果。html不变

这里要用到事件源:event 对象,事件源,不管在哪个事件中,只要你操作的那个元素就是事件源。ie:window.event.srcElement标准下:event.targetnodeName:找到元素的标签名
<html><head></head><body><ul id="ul"><li>aaa</li><li>bbb</li><li>ccc</li></ul></body><script>window.onload=function(){   document.getElementById("ul").onmouseover=function(event){        if(event.target&&event.target.nodeName=="LI"){         event.target.style.background="red";      }   }document.getElementById("ul").onmouseout=function(event){     if(event.target&&event.target.nodeName=="LI"){         event.target.style.background="";      }   }}</script></html>




0 0