Home >Web Front-end >JS Tutorial >Why Doesn\'t My `onClick` Event Listener Work in IE8, and How Can I Fix It?
IE8 onClick Event Listener Compatibility Issue
Problem:
In the provided code, the JavaScript event listener for the li element is not functioning in the IE8 browser.
Solution:
IE8 lacks the addEventListener method, so an alternative cross-browser event handling solution is required. The following code provides a polyfill for addEventListener that works in both standard and legacy browsers:
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."; })();
Usage:
In the provided code, replace the getElementById().addEventListener() calls with:
hookEvent(document.getElementById("hd_vertical"), "click", function(e) { // ... });
Additional Notes:
The above is the detailed content of Why Doesn\'t My `onClick` Event Listener Work in IE8, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!