Home > Web Front-end > JS Tutorial > Why Isn\'t My JS `li` onclick Working in IE8?

Why Isn\'t My JS `li` onclick Working in IE8?

Susan Sarandon
Release: 2024-11-27 18:28:16
Original
336 people have browsed it

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.";
})();
Copy after login

Next, use this function to hook up the event listener:

hookEvent(document.getElementById("hd_vertical"), "click", function(e) {
    // Your event handling code here
});
Copy after login

Note:
IE8 also lacks support for getElementsByClassName. Instead, use querySelectorAll or querySelector:

var _url = document.querySelectorAll("." + id)[1].getAttribute('href');
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template