深入浅析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)); } }

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...