简体   繁体   中英

Uncaught ReferenceError: Activetab is not defined

I have this script:

(function Activetab () {
    var tabs = document.getElementsByClassName('tab');

    for (i = 0; i < tabs.length; i++) {
        tabs[i].addEventListener('click', function (e) {
            removeActive();
            e.target.classList.add('active');
         })
    }
})();

function removeActive() {
    var tabs = document.getElementsByClassName('tab');
    for (i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove('active')
    }
}
window.onload = Activetab();
window.onload = removeActive();

For some reason when I try to use window.onload = Activetab(); return

Uncaught ReferenceError: Activetab is not defined

What is wrong? Why window.onload funcion can't listen Activetab function

You're immediately invoking the function Activetab , you need to read more about IIFE (Immediately Invoked Function Expression).

I don't know why do you want to execute that function immediately, but this is probably the approach you're looking for:

function Activetab () {
    var tabs = document.getElementsByClassName('tab');

    for (i = 0; i < tabs.length; i++) {
        tabs[i].addEventListener('click', function (e) {
            removeActive();
            e.target.classList.add('active');
         })
    }
};

function removeActive() {
    var tabs = document.getElementsByClassName('tab');
    for (i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove('active')
    }
}
window.onload = Activetab; // Just assign the function
window.onload = removeActive; // Just assign the function

You have two choices, dont make it an IIFE

function Activetab () {
        var tabs = document.getElementsByClassName('tab');
        for (i = 0; i < tabs.length; i++) {
            tabs[i].addEventListener('click', function (e) {
                removeActive();
                e.target.classList.add('active');
            })
        }
    }

or keep it as an IIFE and remove window.onload = Activetab(); IIFE's are immediately invoked so no need to call it

IIFE's can also be anonymous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM