IE8 onClick 事件監聽器相容性問題
問題:
在提供的程式碼中,Script事件監聽器因為li 元素在IE8中不起作用browser.
解決方案:
IE8 缺少 addEventListener 方法,因此需要替代的跨瀏覽器事件處理解決方案。以下程式碼提供了適用於標準瀏覽器和舊版瀏覽器的addEventListener 的填充:
var hookEvent = (function() { var div; // Standard-compliant browsers function standardHookEvent(element, eventName, handler) { element.addEventListener(eventName, handler, false); return element; } // Legacy IE browsers function oldIEHookEvent(element, eventName, handler) { element.attachEvent("on" + eventName, function(e) { e = e || window.event; e.preventDefault = oldIEPreventDefault; e.stopPropagation = oldIEStopPropagation; handler.call(element, e); }); return element; } function oldIEPreventDefault() { this.returnValue = false; } function oldIEStopPropagation() { this.cancelBubble = true; } div = document.createElement('div'); if (div.addEventListener) { div = undefined; return standardHookEvent; } if (div.attachEvent) { div = undefined; return oldIEHookEvent; } throw "Neither modern event mechanism (addEventListener nor attachEvent) is supported by this browser."; })();
用法:
在提供的程式碼中,取代getElementById().addEventListener ( )呼叫:
hookEvent(document.getElementById("hd_vertical"), "click", function(e) { // ... });
附加註意:
以上是為什麼我的'onClick”事件監聽器在 IE8 中不起作用,如何修復它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!