在大 IE 還存在的時代,事件監聽的綁定要判斷不同的寫法,才有辦法兼容不同的瀏覽器。
if (document.addEventListener) {
this.addEvent = function(elem, type, fn) {
elem.addEventListener(type, fn, false);
return fn;
}
this.removeEvent = function(elem, type, fn) {
elem.removeEventListener(type, fn, false);
}
} else if (document.attachEvent) {
this.addEvent = function(elem, type, fn) {
var bound = function(){
return fn.apply(elem, arguments);
}
elem.attachEvent("on" + type, bound);
return bound;
}
this.removeEvent = function(elem, type, fn) {
elem.detachEvent("on" + type, fn);
}
}
addEvent(window, "load", function(){
var elems = document.getElementsByTagName("div")
for (var i = 0; i < elems.length; i++) (function(elem){
var handler = addEvent(elem, "click", function(){
this.style.backgroundColor = this.style.backgroundColor === "" ? 'green' : '';
removeEvent(elem, "click", handler)
})
})(elems[i])
})
https://developer.mozilla.org/zh-CN/docs/Web/API/Document_Object_Model/Using_the_W3C_DOM_Level_1_Core
https://developer.mozilla.org/zh-CN/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces