【要求】:点击 li 元素,当且只有它的背景变为红色。
【实现】:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.red {
background: red;
}
</style>
</head>
<body>
<ul id="list">
<li>12345</li>
<li>12345</li>
<li>12345</li>
<li>12345</li>
<li>12345</li>
</ul>
<script>
var oList = document.getElementById('list');
oList.addEventListener('click', function(e) {
var target = e.target || e.srcElement;
var oLi = oList.children;
for (var i=0; i< oLi.length; i++) {
oLi[i].className = '';
}
target.className = 'red';
}, false);
</script>
</body>
</html>