js中的事件委托

来源:互联网 发布:南风知我意2七微 编辑:程序博客网 时间:2024/05/29 17:24

简介

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

在介绍事件委托例子之前,先看一个传统做法的例子:

实现功能是点击li,弹出123:<ul id="ul1">    <li>111</li>    <li>222</li>    <li>333</li>    <li>444</li></ul>
window.onload = function(){    var oUl = document.getElementById("ul1");    var aLi = oUl.getElementsByTagName('li');    for(var i=0;i<aLi.length;i++){        aLi[i].onclick = function(){            alert(123);        }    }}

上面的代码的意思很简单,首先要找到ul,然后遍历li,然后点击li的时候,又要找一次目标的li的位置,才能执行最后的操作,每次点击都要找一次li。如果用事件委托,我们应该用以下的写法:

window.onload = function(){    var oUl = document.getElementById("ul1");   oUl.onclick = function(){        alert(123);    }}

例子详解

对于上面的问题,如果我们ul有很多子元素li、input之类的,而我们只想让ul的li子元素触发onclick函数,应该怎么做。

Event对象提供了一个属性叫target,可以返回事件的目标节点,我们成为事件源,也就是说,target就可以表示为当前的事件操作的dom,但是不是真正操作dom,当然,这个是有兼容性的,标准浏览器用ev.target,IE浏览器用event.srcElement,此时只是获取了当前节点的位置,并不知道是什么节点名称,这里我们用nodeName来获取具体是什么标签名,这个返回的是一个大写的,我们需要转成小写再做比较(习惯问题):

window.onload = function(){  var oUl = document.getElementById("ul1");  oUl.onclick = function(ev){    var ev = ev || window.event;    var target = ev.target || ev.srcElement;    if(target.nodeName.toLowerCase() == 'li'){            alert(123);         alert(target.innerHTML);    }  }}

上面的例子是说li操作的是同样的效果,要是每个li被点击的效果都不一样,那么用事件委托应该怎么做呢?

<div id="box">        <input type="button" id="add" value="添加" />        <input type="button" id="remove" value="删除" />        <input type="button" id="move" value="移动" />        <input type="button" id="select" value="选择" />    </div>
window.onload = function(){            var oBox = document.getElementById("box");            oBox.onclick = function (ev) {                var ev = ev || window.event;                var target = ev.target || ev.srcElement;                if(target.nodeName.toLocaleLowerCase() == 'input'){                    switch(target.id){                        case 'add' :                            alert('添加');                            break;                        case 'remove' :                            alert('删除');                            break;                        case 'move' :                            alert('移动');                            break;                        case 'select' :                            alert('选择');                            break;                    }                }            }        }

总结:

那什么样的事件可以用事件委托,什么样的事件不可以用呢?

适合用事件委托的事件:click,mousedown,mouseup,keydown,keyup,keypress。

值得注意的是,mouseover和mouseout虽然也有事件冒泡,但是处理它们的时候需要特别的注意,因为需要经常计算它们的位置,处理起来不太容易。

不适合的就有很多了,举个例子,mousemove,每次都要计算它的位置,非常不好把控,在不如说focus,blur之类的,本身就没用冒泡的特性,自然就不能用事件委托了。

参考文章地址:
http://www.cnblogs.com/liugang-vip/p/5616484.html