事件委托:
利用冒泡的原理,将事件加到父级,触发执行效果
好处:
1、提高性能(因为是加到父级,不用循环操作)
2、新添加的元素也有事件
事件委托用到的知识:
事件源:
ev = ev || event;
target = ev.target || ev.srcElement; IE下是srcElement,标准的是target
判断事件源对象:nodeName
例如:if (target.nodeName.toLowerCase() == 'li') {},nodeName是大写,需要用toLowerCase转换成小写
<body> <input type='button' value="添加" id='input1'> <ul id="ul1"> <li>111</li> <li>222</li> <li>333</li> <li>444</li> <li>555</li> </ul> <script type="text/javascript"> var oUl = document.getElementById('ul1'); var oInput = document.getElementById('input1'); var iNow = 5; oUl.onmouseover = function(ev){ var ev = ev || event; var target = ev.target || ev.srcElement; if (target.nodeName.toLowerCase() == 'li') { target.style.background = 'red'; } }; oUl.onmouseout = function(ev){ var ev = ev || event; var target = ev.target || ev.srcElement; if (target.nodeName.toLowerCase() == 'li') { target.style.background = ''; } }; oInput.onclick = function(){ iNow++; var oLi = document.createElement('li'); oLi.innerHTML = 111* iNow ; oUl.appendChild(oLi); }; </script> </body>
文章:http://bbs.miaov.com/forum.php?mod=viewthread&tid=5598&highlight=%E4%BA%8B%E4%BB%B6%E5%A7%94%E6%89%98
JQ的事件委托:
delegate()
undelegate()
$('li').click(function(){}) $('li').on('click',function(){}) =>li加事件,有循环
$('ul').delegate('li','click',function(){}) =>ul加事件,这是事件委托