加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

javascript 三种事件监听

发布时间:2020-12-15 01:22:52 所属栏目:C语言 来源:网络整理
导读:第一种监听方式,也是最普遍使用的方式,是直接在代码上加载事件,产生效果: 第二种监听方式,是使用DOM的方式获取对象,并加载事件: 第三种监听方式,是使用标准的addEventListener方式和IE私有的attachEvent方式,因为IE的attachEvent方式在参数传递时的

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

 
   

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



var doms = document.getElementsByTagName('tr');
for (var i = 0; i < doms.length; i++) {
    doms[i].onmouSEOver = function() {
        this.style.backgroundColor = "red";
    }
    doms[i].onmouSEOut = function() {
        this.style.backgroundColor = "green";
    }
}


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



  var 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 = "green";
}

function for_ie(where,how) {
return function() {
how(where);
}
}

for (var 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',hide_color));
}
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读