forked from qianguyihao/Web
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
911 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
|
||
|
||
## 绑定事件的两种方式 | ||
|
||
我们在上一篇文章中已经讲过事件的概念。这里讲一下注册事件的两种方式,我们以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 | ||
|
||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.