**
js中事件委托
**
**
概念
事件的委托是指利用冒泡的原理,把事件加到父级上,触发执行效果。
好处:
- 提高性能
案例
首先看不使用事件委托时的代码 如下:
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
li {
list-style: none;
width: 200px;
line-height: 35px;
border: 1px solid black;
margin: 2px 0;
text-align: center;
}
</style>
</head>
<body>
<ul class="menu">
<li class="lilist">菜单1</li>
<li class="lilist">菜单2</li>
<li class="lilist">菜单3</li>
<li class="lilist">菜单4</li>
<li class="lilist">菜单5</li>
<li class="lilist">菜单6</li>
<li class="lilist">菜单7</li>
<li class="lilist">菜单8</li>
</ul>
<script>
var lilist=document.getElementsByClassName("lilist");
for(var i=0;i<lilist.length;i++){
lilist[i].onclick=function(){
this.style.backgroundColor="red";
}
}
</script>
</body>
</html>
使用事件委托时 如下:
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
li {
list-style: none;
width: 200px;
line-height: 35px;
border: 1px solid black;
margin: 2px 0;
text-align: center;
}
</style>
</head>
<body>
<ul class="menu">
<li class="lilist">菜单1</li>
<li class="lilist">菜单2</li>
<li class="lilist">菜单3</li>
<li class="lilist">菜单4</li>
<li class="lilist">菜单5</li>
<li class="lilist">菜单6</li>
<li class="lilist">菜单7</li>
<li class="lilist">菜单8</li>
</ul>
<script>
var menu = document.getElementsByClassName("menu");
menu[0].onclick = function (event) {
var target = event.target;
if (target.nodeName.toLowerCase() == "li") {
target.style.backgroundColor = "red";
}
}
</script>
</body>
</html>