IE8 onClick 事件监听器兼容性问题
问题:
在提供的代码中,JavaScript 事件监听器因为 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中文网其他相关文章!