事件委托和事件冒泡
<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>
JQ:
<ul id="ulBox">
<li data-id="1"></li>
<li data-id="2"></li>
<li data-id="3"></li>
</ul>
$("#ulBox").on('click','li',function(){
console.log($(this).attr("data-id"));
})