先大概了解一下:
事件委托(代理) : 利用的就是冒泡操作
1.性能要好
2.针对新创建的元素,直接可以拥有事件。
所以有时候需要通过循环节点来绑定事件的话,那请用事件委托吧,这样性能更好哦,当然JQ里面本身就是有delegate,on这些方法了,但是原生的话,做一下兼容性处理就好了。主要以一个例子学习一下。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div> <ul id="list"> <li> <input type="checkbox">复选框 <div class="add"> <a href="#@" class="add">增加</a> <a href="#@" class="delete">删除</a> </div> </li> </ul> </div> <div id="all"> <a href="javascript:;" id="select">全选</a> <a href="javascript:;" id="remove">删除</a> </div> <script> 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; } }, 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; } } }; var temp = 0; var olist = document.getElementById('list'), oall = document.getElementById('all'), oselect = document.getElementById('select'), oremove = document.getElementById('remove'), oInput = olist.getElementsByTagName('input'); function handler(){ var e = arguments[0] || window.event, node = e.srcElement?e.srcElement:e.target, nodeTag = node.nodeName.toLowerCase(), nodeClass = node.className, targetNode = node.parentNode.parentNode, minLen = olist.getElementsByTagName('li').length; if(nodeTag == 'a' && nodeClass == 'add'){ //增加节点 olist.appendChild(olist.getElementsByTagName("li")[0].cloneNode(true)); } else if(nodeTag == 'a' && nodeClass == 'delete'){ //删除节点 if(minLen > 1){ olist.removeChild(targetNode); } } else { return; } } function setInnerText(element, text) { if (typeof element.textContent == "string") { element.textContent = text; } else { element.innerText = text; } } function select(){ var e = arguments[0] || window.event, node = e.srcElement?e.srcElement:e.target; if(temp == 0){ temp = 1; setInnerText(node,'反选'); for(var i=1; i<=oInput.length; i+=1){ oInput[i-1].checked = true; } } else { temp = 0; setInnerText(node,'全选'); for(var i=1; i<=oInput.length; i+=1){ oInput[i-1].checked = false; } } } function removeAll(){//倒序删除节点,避免删不完整 for(var i = oInput.length - 1; i >= 0; i--) { if(oInput[i].checked == true && oInput.length > 1){ olist.removeChild(oInput[i].parentNode); } } } eventUtil.addHandler(olist,"click",handler);//绑定增加删除的方法 eventUtil.addHandler(oselect,'click',select);//绑定全选反选方法 eventUtil.addHandler(oremove,'click',removeAll);//绑定删除方法 </script> </body> </html>