利用事件冒泡,将子级的事件委托给父级加载
利用事件函数中 e 参数,内部存储的是事件对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
li{
padding-left: 20px;
cursor: pointer;
}
ul{margin: 50px auto;
font-size: 24px;
line-height: 48px;
list-style: note;
}
</style>
</head>
<body>
<ul id="list">
<li>是是是</li>
<li>去去去</li>
<li>嘻嘻嘻</li>
<li>哦哦哦</li>
</ul>
<script>
var list = document.getElementById("list");
var lis = list.children;
//给ul添加点击事件
list.onclick = function(e){
for(var i = 0; i < lis.length; i++){
lis[i].style.backgroundColor = "";
}
e.target.style.backgroundColor = "pink";
};
</script>
</body>
</html>