事件委托
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > <title></title> </head> <body> <ul id="myLinks"> <li id="goSomewhere">Go somewhere</li> <li id="doSomething">Do something</li> <li id="sayHi">Say hi</li> </ul> <script type="text/javascript"> window.onload= function() { var list = document.getElementById("myLinks"); addHandler(list, "click", function(ev) { var oEvent = ev||event; var target = getTarget(oEvent); switch(target.id) { case "doSomething": document.title = "I changed the document's title"; break; case "goSomewhere": location.href = "http://www.baidu.com"; break; case "sayHi": alert("hi"); break; } }) } function getTarget(event) { return event.target || event.srcElement; } function addHandler(element, type, handler) { if(element.addEventListener) { element.addEventListener(type, handler, false);//IE9、ff、sa、op、ch }else if (element.attachEvent) { element.attachEvent("on" + type, handler);//IE、op }else { element["on" + type] = handle; } } </script> </body> </html>
事件委托的优点:只为<ul>元素添加事件处理程序,列表项为子节点,事件会冒泡,事件处理程序会执行,至取得了一个DOM元素,只添加了一个事件处理函数,结果相同但所占用的内存更少。