事件委托:利用冒泡的原理,把事件加到父级上,触发执行效果。避免事件处理程序过多影响性能。
把事件绑定在父元素上,点击子元素后冒泡到父元素,再触发父元素的绑定事件。
好处: 1.提高性能。
var uli = document.getElementById("uli");
EventUtil.addHandler(uli, "mouseover", function(event){
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
if(target.nodeName.toLowerCase() == "li") {
target.style.color = "red";
}
});
EventUtil.addHandler(uli, "mouseout", function(event){
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
if(target.nodeName.toLowerCase() == "li") {
target.style.color = "";
}
});
2.新添加的元素保持先前的事件。
不用事件委托添加子元素:不能改变新添加的子元素的样式。
var uli = document.getElementById("uli");
var lis = uli.getElementsByTagName("li");
var myBtn = document.getElementById("myBtn");
for(var i = 0, len = lis.length; i < len; i++) {
lis[i].onmouseover = function(){
this.style.color = "red";
};
lis[i].onmouseout = function(){
this.style.color = "";
};
}
EventUtil.addHandler(myBtn, "click", function(){
var newLi = document.createElement("li");
newLi.innerHTML = "new";
uli.appendChild(newLi);
});
事件委托:新添加子元素样式不变。
var uli = document.getElementById("uli");
EventUtil.addHandler(uli, "mouseover", function(event){
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
if(target.nodeName.toLowerCase() == "li") {
target.style.color = "red";
}
});
EventUtil.addHandler(uli, "mouseout", function(event){
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
if(target.nodeName.toLowerCase() == "li") { //toLowerCase(): 转换为小写字母
target.style.color = "";
}
});
EventUtil.addHandler(myBtn, "click", function(){
var newLi = document.createElement("li");
newLi.innerHTML = "new";
uli.appendChild(newLi);
});
网友评论