最近这段时间因为每天要修改网站,为网站做特效,所以看了很多的 js 接触事件,自己只会使用一小部分,有时用的时候也比较混乱,现在系统的整理了一下,本篇文章跟大家分享的是 JavaScript 中对事件的三种监听方式
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
事件 (Event) 是 JavaScript 应用跳动的心脏,也是把所有东西粘在一起的胶水,当我们与浏览器中 web 页面进行某些类型的交互时,事件就发生了。
第一种监听方式,也是最普遍使用的方式,是直接在代码上加载事件,产生效果:
- <table>
- <tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'>
- <td>
- text1
- </td>
- <td>
- text2
- </td>
- </tr>
- <tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'>
- <td>
- text3
- </td>
- <td>
- text4
- </td>
- </tr>
- <tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'>
- <td>
- text5
- </td>
- <td>
- text5
- </td>
- </tr>
- </table>
第二种监听方式,是使用 DOM 的方式获取对象,并加载事件:
- <table>
- <tr>
- <td>
- text1
- </td>
- <td>
- text2
- </td>
- </tr>
- <tr>
- <td>
- text3
- </td>
- <td>
- text4
- </td>
- </tr>
- <tr>
- <td>
- text5
- </td>
- <td>
- text5
- </td>
- </tr>
- </table>
- <script>
- doms = document.getElementsByTagName('tr');
- for (i = 0; i < doms.length; i++) {
- doms[i].onmouseover = function() {
- this.style.backgroundColor = "red";
- }
- doms[i].onmouseout = function() {
- this.style.backgroundColor = "";
- }
- }
- </script>
第三种监听方式,是使用标准的 addEventListener 方式和 IE 私有的 attachEvent 方式,因为 IE 的 attachEvent 方式在参数传递时的缺陷,这个问题被搞得稍许有些复杂了:
- <table>
- <tr>
- <td>
- text1
- </td>
- <td>
- text2
- </td>
- </tr>
- <tr>
- <td>
- text3
- </td>
- <td>
- text4
- </td>
- </tr>
- <tr>
- <td>
- text5
- </td>
- <td>
- text5
- </td>
- </tr>
- </table>
- <script>
- doms = document.getElementsByTagName('tr');
- function show_color(where) {
- this.tagName ? where = this: null where.style.backgroundColor = "red";
- }
- function hide_color(where) {
- this.tagName ? where = this: null where.style.backgroundColor = "";
- }
- function for_ie(where, how) {
- return function() {
- how(where);
- }
- }
- for (i = 0; i < doms.length; i++) {
- try {
- doms[i].addEventListener('mouseover', show_color, false);
- doms[i].addEventListener('mouseout', hide_color, false);
- } catch(e) {
- doms[i].attachEvent('onmouseover', for_ie(doms[i], show_color));
- doms[i].attachEvent('onmouseout', for_ie(doms[i], hide_color));
- }
- }
- </script>
在绑定多个相同的事件的时候,前两种方法会产生覆盖,而第三中方法则会同时执行多个事件。
来源: http://www.phperz.com/article/17/0226/269236.html