Home > Article > Web Front-end > Why Isn\'t My JS `li` onclick Working in IE8?
JS li onclick Not Working on IE8
Problem:
In the provided code, the li element's click event is not triggering in Internet Explorer 8.
Solution:
IE8 does not support addEventListener. Instead, use its non-standard predecessor, attachEvent.
Code Modification:
First, create a function to handle event hookup:
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."; })();
Next, use this function to hook up the event listener:
hookEvent(document.getElementById("hd_vertical"), "click", function(e) { // Your event handling code here });
Note:
IE8 also lacks support for getElementsByClassName. Instead, use querySelectorAll or querySelector:
var _url = document.querySelectorAll("." + id)[1].getAttribute('href');
The above is the detailed content of Why Isn\'t My JS `li` onclick Working in IE8?. For more information, please follow other related articles on the PHP Chinese website!