[英]“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. 我正在尝试使用布尔值设置变量(currentState),但似乎条件条件中无法识别该变量。 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! @Barmar谢谢! Moved the "currentState" var outside like this:
像这样将“ currentState”变量移到外部:
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))"')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.