现在我们要点击列表取出里面的内容,传统的方法,我们需要遍历添加所有li元素:
<ul id="nav"> <li><a href="http://www.mysupa.com" target="_blank">超级经纪人</a></li> <li>博客园</li> <li>百度</li> <li>新浪</li> <li>搜狐</li> </ul> <script type="text/javascript"> window.onload = function(){ var nav = document.getElementById("nav"); var links = nav.getElementsByTagName("a"); for (var i=0,l = links.length; i<l; i++) { links[i].onclick = function () { alert(this.innerHTML); } } } </script>
新方法使用事件委托
<ul id="nav"> <li><a href="http://www.mysupa.com" target="_blank">超级经纪人</a></li> <li>博客园</li> <li>百度</li> <li>新浪</li> <li>搜狐</li> </ul> <script type="text/javascript"> window.onload = function(){ var nav = document.getElementById("nav"); nav.onclick = function (e) { var e = e || window.event, target = e.srcElement ? e.srcElement : e.target; if(target.nodeName=='LI'){ alert(target.innerHTML) } } } </script>
Dom2的事件委托
var EventUtil = { addHandler: function(element, type, handler){ if (element.addEventListener){ element.addEventListener(type, handler, false); } else if (element.attachEvent){ element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, getEvent: function(event){ return event ? event : window.event; }, getTarget: function(event){ if (event.target){ return event.target; } else { return event.srcElement; } }, preventDefault: function(event){ if (event.preventDefault){ event.preventDefault(); } else { event.returnValue = false; } }, 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; } }, stopPropagation: function(event){ if (event.stopPropagation){ event.stopPropagation(); } else { event.cancelBubble = true; } } }; (function(){ var ul = document.getElementById('nav'); EventUtil.addHandler(ul,'click',function(e){ var e = EventUtil.getEvent(e); var getTarget = EventUtil.getTarget(e); if( getTarget.nodeName =='LI'){ alert(getTarget.innerHTML) } }) })();