javascript事件

事件:

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" id="btn" value="点我">

<div id="main">1111</div>
<script>
// 事件:当什么时候做什么事情
// 触发-响应
//1 获取按钮
var btn = document.getElementById('btn');
//2 给按钮注册事件
//事件名称 click
//事件源:谁触发的事件
//事件处理函数:
btn.onclick = function () {
alert('别点我,疼');
}


// 给div注册事件
var div = document.getElementById('main');
div.onclick = function () {
alert('我是div');
}
</script>
</body>
</html>

图片切换案例:

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="btn">点我</button>
<br>
<img id="mv" width="400" height="300" src="images/a.jpg" alt="">
<script>
var btn = document.getElementById('btn');
var mv = document.getElementById('mv');

var flag = 1;
btn.onclick = function () {
if (flag === 1) {
mv.src = 'images/b.jpg';
flag = 2;
} else if (flag === 2) {
mv.src = 'images/a.jpg';
flag = 1;
}
}

</script>
</body>
</html>