事件委托能够优化js性能

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>面试题练习img居中</title>

<style type="text/css">

img {

/*display: table-cell;

vertical-align: middle;*/

}

html,body{

height: 100%;

}

div{

width: 600px;

height: 1600px;

display: table-cell;

vertical-align: middle;

text-align: center;

}

</style>

</head>

<body>

<ul>

<li id="a">1</li>

<li id="b">2</li>

<li id="c">3</li>

<li id="d">4</li>

<li id="e">5</li>

</ul>

</body>

<script type="text/javascript">

var str = document.getElementsByTagName("ul")[0];

str.onclick = function(){

var hehe = event || window.event;

var target = hehe.target || hehe.srcElement;

switch(target.id){

case "a":{

console.log(1);

this.style.background = "orange";

break;

}

case "b":{

console.log(2);

this.style.background = "orange";

break;

}

case "c":{

console.log(3);

this.style.background = "orange";

break;

}

case "d":{

console.log(4);

this.style.background = "orange";

break;

}

case "e":{

console.log(5);

this.style.background = "orange";

break;

}

}

}

</script>

</html>

使用事件委托以后,可以不必在每个子元素上绑定事件,能够优化性能,同时对于一些动态添加进去的子元素,事件委托也要比执行回调函数绑定事件更加方便

上一篇:三十天学不会TCP,UDP/IP网络编程-UDP,从简单的开始


下一篇:box-sizing (摘录)