JavaScript事件委托

2017-07-29  本文已影响35人  07120665a058

JavaScript事件委托

<ul id="ul1"> 
  <li>111</li>
  <li>222</li>
  <li>333</li>
  <li>444</li>
</ul>
//给每个li都绑定事件
window.onload = function(){ 
  let oUl = document.getElementById("ul1");
  let aLi = oUl.getElementsByTagName('li');
  for(let i=0;i<aLi.length;i++){
    aLi[i].onclick = function(){
      console.log(aLi[i].innerText);
    }
  }
}
//把所有的li事件都委托给父级ul来处理
window.onload = function(){
  let ul = document.getElementById("ul1");
  ul.onclick = function(event){
    let e = event || window.event;
   //标准浏览器用e.target,IE浏览器用event.srcElement
    let target = e.target || e.srcElement; 
    if(target.nodeName.toLowerCase() == 'li'){
        alert(target.innerHTML);
    }
  }
}
上一篇下一篇

猜你喜欢

热点阅读