IE8及更早的版本不支持 addEventListener()函數,所以須要一個標準的函數將這些差別性作封裝:函數
1 function addListener(target, type, handler) { 2 if (target.addEventListener) { 3 target.addEventListener(type, handler, false); 4 } else if (target.attachEvent) { 5 target.attachEvent("on" + type, handler); 6 } else { 7 target["on" + type] = handler; 8 } 9 }
使用 addListener()函數:spa
1 function doSomeThing() { 2 // 代碼 3 } 4 var btn = document.getElementById("action-btn"); 5 addListener(btn, "click", doSomeTing);