var ulBox = document.getElementById("ulBox"); var li = document.getElementsByTagName("li"); var l = li.length; for(i=0;i li[i].Onmouseover=function(){ this.style.background="red"; } li[i].Onmouseout=fucntion(){ this.style.background=""; } }
这样,我们已经为每个
都添加了事件,但是,这个事件循环了 i 次,比较消耗性能。
用事件代理也可以实现同样的效果
var ulBox = document.getElementById("ulBox"); ulBox.Onmouseover= function(e){ var hover = e||window.event;//获取事件对象, var nodeLi = hover.target||hover.srcElement;//获取事件对象的具体子元素 nodeLi.style.background="red"; } ulBox.Onmouseout= function(e){ var hover = e||window.event;//获取事件对象, var nodeLi = hover.target||hover.srcElement;//获取事件对象的具体子元素 nodeLi.style.background="red"; }
如果我们要追加几个
,使用一个
Event commission
mountain
leopard
tiger
Stalin
Hitler
Barton
如果使用常规方法
var ulBox = document.getElementById("ulBox"); var li = document.getElementsByTagName("li"); var btn = document.getElementById("btn"); var l = li.length; for(i=0;i li[i].Onmouseover=function(){ this.style.background="red"; } li[i].Onmouseout=fucntion(){ this.style.background=""; } btn.Onclick=function(){ var oLi = document.createElement("li"); oLi.innerHTML="Low"; ulBox.appendChild(oLi); } }
新加入的
并不能响应滑过变色的事件,因为在添加完元素之前,循环已经执行完毕。
使用事件委托,即可以直接响应事件效果
ulBox.Onmouseover=function(e){ var hover=e||window.event; var nodeLi=hover.target||hover.srcElement; nodeLi.style.background="red"; } ulBox.Onmouseout=function(e){ var hover=e||window.event; var nodeLi=hover.target||hover.srcElement; nodeLi.style.background=""; }
btn.Onclick=function(){ var oLi = document.createElement("li"); oLi.innerHTML="Low"; ulBox.appendChild(oLi); }