简体   繁体   中英

“Toggle state”-variable in javascript?

I'm trying to set a variable (currentState) with a boolean but it doesn't seem like the variable is recognized within the conditionals. What am I missing?

function toggle(customID) { // Function set on button, 'customID' is the ID
                            // of element to toggle with button. Ex:
                            // <button onclick="(toggle('menu')">Button</button>
    var theToggledElement = document.getElementById(customID);
    var currentState = false; // false = hidden. true = visible.

    if (currentState === false) {
        currentState = true;
        theToggledElement.style.left = '0px';
        console.log('State set to "visible" and left to "0px"');
    }
    else if (currentState === true) {
        currentState = false;
        theToggledElement.style.left = 'calc(-100% + (0.5cm + 1.461544602cm + .5cm))';
        console.log('State set to "hidden" and left to "calc(-100% + (0.5cm + 1.461544602cm + .5cm))"')
    }
}

在此处输入图片说明

@Barmar thank you! Moved the "currentState" var outside like this:

var currentState = false; // false = hidden. true = visible.
function toggle(customID) { // Function set on button, 'customID' is the ID
                            // of element to toggle with button. Ex:
                            // <button onclick="(toggle('menu')">Button</button>
    var theToggledElement = document.getElementById(customID);

    if (currentState === false) {
        currentState = true;
        theToggledElement.style.left = '0px';
        console.log('State set to "visible" and left to "0px"');
    }
    else if (currentState === true) {
        currentState = false;
        theToggledElement.style.left = 'calc(-100% + (0.5cm + 1.461544602cm + .5cm))';
        console.log('State set to "hidden" and left to "calc(-100% + (0.5cm + 1.461544602cm + .5cm))"')
    }
}

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