例子6:获取事件源和访问相关元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#buttons>button {
border: none;
outline: none;
width: 120px;
height: 40px;
font: 22px/40px Arial;
background-color: red;
color: white;
margin-top: 20px;
}
</style>
</head>
<body>
<div id="buttons">
<button><input type="checkbox">苹果</button>
<button><input type="checkbox">香蕉</button>
<button><input type="checkbox">草莓</button>
<button><input type="checkbox">蓝莓</button>
<button><input type="checkbox">榴莲</button>
<button><input type="checkbox">西瓜</button>
<button><input type="checkbox">芒果</button>
<button><input type="checkbox">柠檬</button>
</div>
<script>
var buttons = document.querySelectorAll('#buttons>button');
for (var i = 0; i < buttons.length; i += 1) {
buttons[i].firstChild.addEventListener('click', function(evt) {
var checkbox = evt.target || evt.srcElement;
if (checkbox.checked) {
checkbox.parentNode.style.backgroundColor = 'lightseagreen';
} else {
checkbox.parentNode.style.backgroundColor = 'red';
}
evt.stopPropagation();
});
buttons[i].addEventListener('click', function(evt) {
// 通过事件对象的target属性可以获取事件源(谁引发了事件)
// 但是有的浏览器是通过srcElement属性获取事件源的
// 可以通过短路或运算来解决这个兼容性问题
var button = evt.target || evt.srcElement;
// 当获取到一个元素之后可以通过它的属性来获取它的父元素、子元素以及兄弟元素
// parentNode - 父元素
// firstChild / lastChild / children - 第一个子元素 / 最后一个子元素 / 所有子元素
// previousSibling / nextSibling - 前一个兄弟元素 / 后一个兄弟元素
var checkbox = button.firstChild;
checkbox.checked = !checkbox.checked;
if (checkbox.checked) {
button.style.backgroundColor = 'lightseagreen';
} else {
button.style.backgroundColor = 'red';
}
});
}
</script>
</body>
</html>