事件委托主要解决事件处理程序过多的问题,利用了事件冒泡
<ul id="mylinks"> <li id="gosomewhere">gosomewhere</li> <li id="dosomething">dosomething</li> <li id="sayhi">hi</li> </ul>
传统模式需要添加三个点击事件
var item1 = document.getElementByID("gosomewhere"); var item2 = document.getElementByID("dosomething"); var item2 = document.getElementByID("sayhi"); EventUtil.addHandler(item1,"click",function(event){ loaction.href = "www.baidu.com" }) EventUtil.addHandler(item2,"click",function(event){ document.title = 'i am a new title'; }) EventUtil.addHandler(item3,"click",function(event){ alert('hi'); })
如果是一个复杂的web程序,对每一个可单击的DOM元素都写一个点击事件,会产生很多代码,事件委托只需要在尽量最高的层次上添加一个点击事件
var link= document.getElementByID("mylinks"); EventUtil.addHandler(link,"click",function(event){ event = EventUtil.getEvent(event); target =EventUtil.getTarget(event); switch(target.id) { case 'gosomewhere': loaction.href = "www.baidu.com"; break; case 'dosomething': document.title = 'i am a new title'; break; case 'sayhi': alert('hi') break; } })