【问题标题】:Changing boolean value on document click更改文档单击时的布尔值
【发布时间】:2017-08-17 13:59:25
【问题描述】:

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

$(document).ready(function(){    

  var abc = false;

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

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


});

有人帮忙吗?谢谢

【问题讨论】:

  • 您需要将if 语句within 放在click 处理程序中,否则它只会在页面加载时运行。事实上,整个abc 布尔标志和if 条件逻辑是完全多余的——只需在点击处理程序中调用你的alert()
  • 为什么你不把警报放在点击功能中

标签: javascript jquery boolean var


【解决方案1】:

这是由使用 event model 的 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>

【讨论】:

  • 这有点重复:)
  • This is caused by JavaScript being asynchronous 不,不是。它是由使用事件模型的 Javascript 引起的。
  • @RoryMcCrossan 是的,很抱歉解释错误。
  • 非常感谢您的回答,它工作正常。但有了这个,我不能做我想做的事。我的目标是创建一个变量,当我点击我的文档时它是正确的,当我不点击时它是错误的。之后,我希望仅在 var 错误时触发操作列表 ==> 所以我希望我的操作一直被触发,除非我单击我的文档。我觉得我用的方法不是很好 X)
【解决方案2】:

您的警报不会启动,因为它不在点击处理程序中。它仅在文档加载并保持平静时执行一次。你应该把你的检查移到点击里面

$(document).click(function(){
   abc = true;
  if (abc == true){
   alert("ALERT"); 
   //do some other things
 }
  });

此外,对于布尔值,您可以直接在 if 条件中写入变量名称,就好像无论如何都期望布尔值一样

if (abc == true){

可以缩短为

if (abc){

所以,在把你所有的部分放在一起之后,

$(document).ready(function() {
    var abc = false;

    $(document).click(function() {

        abc = true;

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

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 2019-04-17
    • 2019-05-01
    相关资源
    最近更新 更多