Skip to content

Commit

Permalink
update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
smyhvae committed Feb 2, 2018
1 parent 16dfec3 commit 2640f6b
Show file tree
Hide file tree
Showing 5 changed files with 911 additions and 4 deletions.
144 changes: 144 additions & 0 deletions 03-JavaScript基础/09-事件.md
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

```

Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ document.write();

效果如下:

20180129_1908.png
![](http://img.smyhvae.com/20180129_1908.png)


**方式二:**innerHTML
Expand Down Expand Up @@ -77,7 +77,7 @@ document.write();

效果如下:

20180129_2017.png
![](http://img.smyhvae.com/20180129_2017.png)



Expand Down Expand Up @@ -109,7 +109,9 @@ document.write();

现在要做下面这样一个页面:

20180129_2151.png

![](http://img.smyhvae.com/20180129_2151.png)


上图的意思是,每次刷新页面,都从服务器获取最新的在线人数的名单(我们先用本地的数组来模拟服务器上的数据)。

Expand Down Expand Up @@ -334,12 +336,17 @@ document.write();
</html>
```

工程文件:

- [2018-02-01-获取在线用户列表demo.rar](http://download.csdn.net/download/smyhvae/10237611)



## innerHTML举例2:模拟百度搜索的下方提示

要求实现的效果如下:

20180201_2030.gif
![](http://img.smyhvae.com/20180201_2030.gif)

在这之前,我们先实现这样一个例子:**判断字符串以某个字符串为开头**

Expand Down
Loading

0 comments on commit 2640f6b

Please sign in to comment.