简体   繁体   中英

Global variable not updating in javascript

I've seen several posts on here about how to update a Javascript global variable. I'm trying to use it as a toggle, so that when the function runs again it does the opposite of what it just did (or, that is, whatever I've set it to do. )

It's not working, and I'm frusturated because I'm getting no errors from the developer console, either.

var display_menu_toggle = false;
function display_menu() {
        if (display_menu_toggle == true) {
        document.getElementById('barometer').style.display = "none";
        document.getElementById('finance').style.display = "none";
        return false;
    }
    document.getElementById('barometer').style.display = "block";
    document.getElementById('finance').style.display = "block";
    display_menu_toggle = true;
    return true;
}

As others have said, you aren't changing the value of display_menu_toggle for both conditions. Consider:

var display_menu_toggle = false;

function display_menu() {
    document.getElementById('barometer').style.display = display_menu_toggle? "none" : '';
    document.getElementById('finance').style.display = display_menu_toggle? "none" : '';
    display_menu_toggle = !display_menu_toggle;
}

It's usually best to toggle style.display between none and '' (empty string) so that when not hidden, the element returns to its default or inherited style, whatever that might be.

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