JS li Tag Onclick Event Not Functioning in IE8
The issue reported with the li onclick event failing to function in IE8 browsers stems from the fact that IE8 doesn't support the addEventListener method. To address this, we need to utilize its non-standard predecessor, attachEvent.
Implementing the attachEvent Hook
The following hookEvent function can be used to handle events in both standard-compliant browsers and those with the previous Microsoft-specific mechanism:
var hookEvent = (function() { var div; function standardHookEvent(element, eventName, handler) { element.addEventListener(eventName, handler, false); return element; } 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."; })();
Integrating the Hook into Event Handling
To use this hook in the provided example, we replace the addEventListener line with:
hookEvent(document.getElementById("hd_vertical"), "click", function(e) { // Event handling code });
Additional Considerations
IE8 also lacks support for getElementsByClassName. To compensate, we can use querySelectorAll or querySelector instead:
var _url = document.querySelectorAll("." + id)[1].getAttribute('href'); // Grabs the second matching element var _url = document.querySelector("." + id).getAttribute('href'); // Grabs the first matching element
By leveraging the hookEvent function and addressing these additional IE8 browser compatibility issues, the li onclick event should now function as expected.
The above is the detailed content of Why Doesn\'t My JS `li` Tag\'s `onclick` Event Work in IE8, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!