标签:
什么是事件委托:通俗的讲,事件就是onclick,onmouseover,onmouseout等,委托呢,就是让别人来做,这个事件本来是加在某些元素上的,然而你却加到别人身上来做,完成这个事件。
原理:
利用冒泡的原理,把事件加到父级上,触发执行效果。
作用:
1.性能要好
2.针对新创建的元素,直接可以拥有事件
事件源 :
跟this作用一样(他不用看指向问题,谁操作的就是谁),event对象下的
使用情景:
•为DOM中的很多元素绑定相同事件;
•为DOM中尚不存在的元素绑定事件;
JS的事件委托
例子:需要触发每个li来改变他们的背景颜色。
<ul id="ul">
<li>aaaaaaaa</li>
<li>bbbbbbbb</li>
<li>cccccccc</li>
</ul>
window.onload = function(){
var oUl = document.getElementById("ul");
var aLi = oUl.getElementsByTagName("li");
/*
这里要用到事件源:event 对象,事件源,不管在哪个事件中,只要你操作的那个元素就是事件源。
ie:window.event.srcElement
标准下:event.target
nodeName:找到元素的标签名
*/
oUl.onmouseover = function(ev){
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
//alert(target.innerHTML);
if(target.nodeName.toLowerCase() == "li"){
target.style.background = "red";
}
}
oUl.onmouseout = function(ev){
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
//alert(target.innerHTML);
if(target.nodeName.toLowerCase() == "li"){
target.style.background = "";
}
}
}
Jquery的事件委托
$(function(){
$(‘#ul1,#ul2‘).delegate(‘li‘,‘click‘,function(){
if(!$(this).attr(‘s‘)) {
$(this).css(‘background‘,‘red‘);
$(this).attr(‘s‘,true);
}else {
$(this).css(‘background‘,‘#fff‘);
$(this).removeAttr(‘s‘);
}
})
});
最新on()方法取替了delegate()方法
$(function(){
$(‘#ul1,#ul2‘).on(‘click‘,‘li‘,function(){
if(!$(this).attr(‘s‘)) {
$(this).css(‘background‘,‘red‘);
$(this).attr(‘s‘,true);
}else {
$(this).css(‘background‘,‘#fff‘);
$(this).removeAttr(‘s‘);
}
})
});
标签:
原文地址:http://www.cnblogs.com/baosisi/p/4997033.html