js事件委托和事件冒泡

<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>

猜你喜欢

转载自www.cnblogs.com/yuyedaocao/p/10369558.html
今日推荐