事件委托
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>点我变色!</li>
<li>点我变色!</li>
<li>点我变色!</li>
<li>点我变色!</li>
<li>点我变色!</li>
</ul>
<script>
//事件委托1:我们要对若干li进行事件绑定,但是显然不能一个个绑定,所以我们对ul绑定即可达到效果
/* var ul = document.querySelector('ul');
ul.addEventListener('click', function (e) {
alert('变成粉色!');
e.target.style.backgroundColor = 'pink';
}) */
//事件委托2:委托1+点击后只有点击后的li变成该颜色,其他置空
var ul = document.querySelector('ul');
ul.addEventListener('click', function (e) {
//alert('变成粉色!');
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].style.backgroundColor = '';
e.target.style.backgroundColor = 'pink';
}
})
</script>
</body>
</html>
两种方法,还增加了一些css的小技巧~