javascript - 单击文档更改 boolean 值

标签 javascript jquery boolean var

很抱歉这个非常基本的问题,但它让我发疯,我不明白这个非常简单的 Jquery 代码有什么问题。 我只想在单击我的文档时将我的“abc” boolean 值从 false 更改为 true,并在“abc”为真时启动警报(仅作为示例)。

$(document).ready(function(){    

  var abc = false;

  $(document).click(function(){
   abc = true;
  });

 if (abc == true){
   alert("ALERT"); 
   //do some other things
 }


});

有人帮忙吗?谢谢

最佳答案

这是由 JavaScript 使用事件模型引起的。这是你的一段代码,有详细的解释:

var abc = false;

$(document).click(function() {
  // Note that this function is attached to the `click` event
  // It will be triggered only when the `click` event is triggered
  // This means that the code inside it is not executed at the moment
  abc = true;
});

// abc is false at the moment so the if statement won't execute
if (abc == true) { 
  alert("ALERT"); 
  //do some other things
}

要解决这个问题,只需将 if 语句放在点击处理程序中,它就会正常工作。

$(document).ready(function() {    

  var abc = false;

  $(document).click(function(){
    abc = true;

    if (abc == true){
      alert("ALERT"); 
      //do some other things
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 单击文档更改 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737194/

相关文章:

jquery - 单击并拖动在 Firefox 中不适用于 jQuery UI iframeFix

java - 有没有一种方法可以使用 | 一次比较多个(非 boolean 值)事物?或 & 在 Java 中,类似于如何使用 | 捕获多个异常?

c++ - 仅在线程休眠时评估为真

c - 为什么 (0 < a < 5) 这样的条件总是为真?

javascript - chartjs 3.0 中的 generateLegend() 发生了什么?

javascript - 为多个 Highcharts 创建默认选项

javascript - 如何将变量插入 JavaScript 对象中作为键?

javascript - 完全加载后将事件分配给 div

javascript - 检查输入中是否仅输入了数值。 (jQuery)

javascript - 在不改变 HTML 的情况下使用 CSS 或 JavaScript 将字段输入到下一行