<style> * { margin:0; padding:0; list-style:none; } #ul { 400px; height:250px; margin:0 auto; } </style> </head> <body> <ul id='ul' style='border:1px solid black'>UL <li>LI<a href=''>a</a></li> <li>LI<a href=''>a</a></li> <li>LI<a href=''>a</a></li> <li>LI<a href=''>a</a></li> </ul> <script> var EventUtil = { addHandler : function(element,type,handler){ if (element.addEventListener)//标准 { element.addEventListener(type,handler,false); }else if (element.attachEvent)//老IE { //handler,必须保证this指向调用的对象,因为在IE下指向window element.attachEvent('on'+type,handler); }else { element['on'+type] = handler; } }, removeHandler : function(element,type,handler){ if (element.removeEventListener) { element.removeEventListener(type,handler,false); }else if (element.detachEvent) { element.detachEvent('on'+type,handler); }else { element['on'+type] = null; } }, init: function(arr){ for (var i=0;i<arr.length ;i++ ) { arr[i].style.height = 50+'px'; if (i%2 == 0) { arr[i].style.background = 'red'; }else { arr[i].style.background = 'blue'; } } }, fn: function(event){ var bar = event.target;//返回真正的点击的元素 var tar = bar.nodeName.toLowerCase(); console.log('你点击了:'+tar); event.preventDefault(); } }, oUl = document.getElementById('ul'), aLi = oUl.getElementsByTagName('li'); EventUtil.init(aLi); EventUtil.addHandler(oUl,'click',EventUtil.fn); </script> </body>
target返回的是真正的点击的元素
<style> * { margin:0; padding:0; list-style:none; } #ul { 400px; height:250px; margin:0 auto; } </style> </head> <body> <ul id='ul' style='border:1px solid black'>UL <li>LI<a href=''>a</a></li> <li>LI<a href=''>a</a></li> <li>LI<a href=''>a</a></li> <li>LI<a href=''>a</a></li> </ul> <script> var EventUtil = { addHandler : function(element,type,handler){ if (element.addEventListener)//标准 { element.addEventListener(type,handler,false); }else if (element.attachEvent)//老IE { //handler,必须保证this指向调用的对象,因为在IE下指向window element.attachEvent('on'+type,handler); }else { element['on'+type] = handler; } }, removeHandler : function(element,type,handler){ if (element.removeEventListener) { element.removeEventListener(type,handler,false); }else if (element.detachEvent) { element.detachEvent('on'+type,handler); }else { element['on'+type] = null; } }, init: function(arr){ for (var i=0;i<arr.length ;i++ ) { arr[i].style.height = 50+'px'; if (i%2 == 0) { arr[i].style.background = 'red'; }else { arr[i].style.background = 'blue'; } } }, fn: function(event){ var bar = event.currentTarget;//返回真正的点击的元素 var tar = bar.nodeName.toLowerCase(); console.log('你点击了:'+tar); event.preventDefault(); } }, oUl = document.getElementById('ul'), aLi = oUl.getElementsByTagName('li'); EventUtil.init(aLi); EventUtil.addHandler(oUl,'click',EventUtil.fn); </script> </body>
返回的是绑定的事件的对象和this一样