【问题标题】:Whenever trying to toggle, it always switches to true no matter what way I try to toggle每当尝试切换时,无论我尝试以何种方式切换,它总是切换为 true
【发布时间】:2022-01-25 17:32:09
【问题描述】:

日志

显示日志的代码

所以,我连接了一个 HTML 按钮来运行上面代码中显示的函数,并且我尝试了许多方法,例如使用不同的切换函数,例如 bool = bool ? false : true;,但都没有工作。我试图在其他地方插入hideToggled = !hideToggled,比如 if 函数或 if 函数下方,但似乎都不起作用。任何帮助将不胜感激!

【问题讨论】:

标签: javascript boolean


【解决方案1】:

您在 if 块中分配变量 true/false 值

if (hideToggled = true)

将导致 hideToggled 被赋值为 true

查看下面的工作代码:

let hideToggled = false
let hideButtonText = ''

function toggleHideShow() {
  hideToggled = !hideToggled

  if (hideToggled) {
      hideButtonText = 'Show'
  } else {
      hideButtonText = 'Hide'
  }
}

toggleHideShow()
console.log(hideToggled, hideButtonText)
toggleHideShow()
console.log(hideToggled, hideButtonText)
toggleHideShow()
console.log(hideToggled, hideButtonText)
toggleHideShow()
console.log(hideToggled, hideButtonText)

【讨论】:

  • 谢谢!天哪,我感觉自己像个白痴,忘记了基本语法……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
相关资源
最近更新 更多