Files
web/03-JavaScript基础/09-事件.md
2018-02-02 21:19:12 +08:00

145 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 绑定事件的两种方式
我们在上一篇文章中已经讲过事件的概念。这里讲一下注册事件的两种方式我们以onclick事件为例。
### 方式一onclick
举例:
```html
<body>
<button>点我</button>
<script>
var btn = document.getElementsByTagName("button")[0];
//这种事件绑定的方法容易被层叠。
btn.onclick = function () {
console.log("事件1");
}
btn.onclick = function () {
console.log("事件2");
}
</script>
</body>
```
点击按钮后,上方代码的打印结果:
```html
事件2
```
我们可以看到,这种绑定事件的方式,会层叠掉之前的事件。
### 方式二addEventListener
addEventListener()里的参数:
- 参数1事件名(不带on)
- 参数2事件名(执行函数)
- 参数3事件名(捕获或者冒泡)
举例:
```html
<body>
<button>按钮</button>
<script>
var btn = document.getElementsByTagName("button")[0];
//addEventListener: 事件监听器。 原事件被执行的时候,后面绑定的事件照样被执行
//第二种事件绑定的方法不会出现层叠。(更适合团队开发)
btn.addEventListener("click", fn1);
btn.addEventListener("click", fn2);
function fn1() {
console.log("事件1");
}
function fn2() {
console.log("事件2");
}
</script>
</body>
```
点击按钮后,上方代码的打印结果:
```html
事件1
事件2
```
我们可以看到,这种绑定事件的方式,不会层叠掉之前的事件。
```html
```
```html
```
```html
```
```html
```
```html
```
```html
```
```html
```