每当尝试切换时,无论我尝试以何种方式切换,它总是切换为 true

Whenever trying to toggle, it always switches to true no matter what way I try to toggle

日志

显示日志的代码

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

您正在为 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)