码迷,mamicode.com
首页 > Web开发 > 详细

js事件委托和事件冒泡

时间:2019-02-13 14:19:57      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:classname   nodename   target   img   case   cas   func   div   node   

<div id="ulbox" class="ulbox">
  <a>
    <img src="../../dist/img/77014842_5.jpg" width="30px" />
    <p>aaa</p>
    <span>111</span>
    <input type="radio" name="sex" />
  </a>
  <a>
    <img src="../../dist/img/77014842_5.jpg" width="30px" />
    <p>bbb</p>
    <span>222</span>
    <input type="radio" name="sex" />
  </a>
  <a>
    <img src="../../dist/img/77014842_5.jpg" width="30px" />
    <p>ccc</p>
    <span>333</span>
    <input type="radio" name="sex" />
  </a>
</div>
<script>
var uid = document.getElementById("ulbox");
uid.onclick = function (e) {//使用事件委托给父类执行点击事件
  var ele = e.target;
  for (var i = 0; i < uid.children.length; i++) {
    uid.children[i].className = "";
    uid.children[i].lastElementChild.removeAttribute("checked");
  }
  while (ele.nodeName.toLowerCase() != "div") {//当点击的是a标签内部任意标签,利用冒泡
    if (ele.nodeName.toLowerCase() == "a") {
      break;
    }
    var ele = e.target.parentNode;
  }
  if (ele.nodeName.toLowerCase() != "div") {
    ele.className = "xxxx";
    ele.lastElementChild.setAttribute("checked","checked");
  }
}
</script>

js事件委托和事件冒泡

标签:classname   nodename   target   img   case   cas   func   div   node   

原文地址:https://www.cnblogs.com/yuyedaocao/p/10369558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!