事件委托
- 不用给子元素循环绑定事件,提高性能
- 新添加的子元素,仍能保留原有事件
Event 对象兼容处理
IE :window.event.srcElement
标准:event.target
兼容写法
function(e){
var e = e || window.event;
var target = ev.target || e.srcElement;
alert(target.innerHTML);// 对目标元素处理,检测
}
下面贴一段代码演示
<ul id="ul">
<li>11</li>
<li>22</li>
<li>33</li>
</ul>
var oUl = document.getElementById('ul1');
var aLi = oUl.getElementsByTagName('li');
oUl.onmouseover = function(ev){
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
// 用nodeName节点名判断是子元素还是父元素
if(target.nodeName.toLowerCase() == 'li'){
target.style.background = 'red';
}
};
oUl.onmouseout = function(ev){
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
if(target.nodeName.toLowerCase() == 'li'){
target.style.background = '';
}
};