js事件委托和事件冒泡
Posted 雨夜稻草
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
以上是关于js事件委托和事件冒泡的主要内容,如果未能解决你的问题,请参考以下文章