微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

深入浅析JavaScript中对事件的三种监听方式

事件(Event)是JavaScript应用跳动的心脏,也是把所有东西粘在一起的胶水,当我们与浏览器中Web页面进行某些类型的交互时,事件就发生了。

第一种监听方式,也是最普遍使用的方式,是直接在代码上加载事件,产生效果

rush:xhtml;">

第二种监听方式,是使用DOM的方式获取对象,并加载事件:

rush:js;"> doms = document.getElementsByTagName('tr'); for(i=0;iSEOver = function() { this.style.backgroundColor = "red"; } doms[i].onmouSEOut = function() { this.style.backgroundColor = ""; } }

第三种监听方式,是使用标准的addEventListener方式和IE私有的attachEvent方式,因为IE的attachEvent方式在参数传递时的缺陷,这个问题被搞得稍许有些复杂了:

rush:js;"> 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;iSEOver',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',hide_color)); } }

在绑定多个相同的事件的时候,前两种方法会产生覆盖,而第三中方法则会同时执行多个事件。

原文地址:https://www.jb51.cc/js/52225.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐