第一种监听方式,也是最普遍使用的方式,是直接在代码上加载事件,产生效果:
第二种监听方式,是使用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));
}
}
在绑定多个相同的事件的时候,前两种方法会产生覆盖,而第三中方法则会同时执行多个事件。