简体   繁体   English

全局变量更新不触发jQuery中的if / else语句

[英]global variable update not triggering if/else statement in jquery

See the example below, basically I want it to execute if on the first click, and then for all subsequent clicks to execute the else statement but even though the variable is updating it isn't switching to else eg if the alert message is saying the variable is now at three it still doesn't go to else. 参见下面的示例,基本上,我希望它在第一次单击时执行,然后在所有后续单击中执行else语句,但是即使变量正在更新,也不会切换到else,例如,警报消息说变量现在为三,但仍然没有其他。 I'm guessing it's a scope issue but how do I get around it - can anyone advise? 我猜这是一个范围问题,但是我该如何解决-有人可以建议吗?

var loaded = 0;

if (loaded == 0) {
$('body').on('click', '#button', function(){
alert(loaded);
loaded += 1;
});

} else {
alert(loaded + 'yay its not 0');
};

This should hopefully behave as intended: 希望这应能达到预期的效果:

$(document).ready(function() {
    var clicked = false;
    $('body').click(function() { 
        if(clicked) {
            alert("Already clicked");
        } else {
            alert("Not clicked yet");
            clicked = true;
        }
    });
});

Hope that helped. 希望能有所帮助。

Your if condition only runs one time. 您的if条件仅运行一次。 Try placing your check within the click event: 尝试将支票放入click事件中:

var loaded = 0;
$('body').on('click', '#button', function () {
    if (loaded == 0) {
        alert(loaded);
        loaded += 1;
    } else {
        alert(loaded + 'yay its not 0');
    };
});

jsFiddle example jsFiddle示例

Events dont work like that once its assigned it always runs unless you use .one or manually call .off after the fact - but even then your check will only get executed once when the script loads, not when a click happens. 分配事件后,事件不会像这样正常运行,除非您在事件结束后使用.one或手动调用.off ,否则事件始终会运行-但是即使那样,您的检查也只会在脚本加载时执行一次,而不是在单击时执行。 You need to handle the if/else inside your event handler. 您需要在事件处理程序中处理if / else。

var loaded = 0;
$('body').on('click', '#button', function(){
   if(loaded === 0) {
      alert(loaded);
      loaded += 1;
   } else {

   }
});

Put your check inside the click handler: 将支票放入点击处理程序中:

  $('body').on('click', '#button', function(){
      if(loaded == 0){
          alert(loaded);
          loaded += 1;
      }
      else{
         alert(loaded + 'yay its not 0');

      }
   });

The if statement is only executed the first time, after that you enter the on() method and bind the function to #button , but there's no other evaluation afterwards, in this case it'd only go to the else part if loaded 's initial value wasn't 0, so you should change your code to: if仅在第一次执行if语句,然后输入on()方法并将函数绑定到#button ,但是此后没有其他评估,在这种情况下,如果loaded了,则仅转到else部分初始值不为0,因此您应将代码更改为:

$('body').on('click', '#button', function(){
if (loaded == 0) {
  alert(loaded);
loaded += 1;
  } else {
alert(loaded + 'yay its not 0');
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM