【问题标题】:Variable always evaluates to false变量总是计算为假
【发布时间】:2015-12-15 12:47:26
【问题描述】:

我正在学习 jQuery,我只是在测试事件和条件是如何工作的。我还使用 Velocity.js 来制作动画。这是代码:

$(function() {

$( "#navBar" ).click(function() {
    var isOpen = false;
      if (isOpen == false){
       $( this ).velocity({ height: 300});
          isOpen = true;
          console.log(isOpen);
          return false;
      }
      else{
       $( this ).velocity({ height: 50});
          isOpen = false;
          console.log(isOpen);
      }

   });

});

我不知道为什么这不起作用。 if 条件 被执行并记录到控制台变量为真。但第二次点击后继续运行 if 条件并返回 isOpen true。我无法执行 else 语句。

【问题讨论】:

  • isOpen总是为假。您需要在 click 函数之外声明它。
  • 在按钮点击外保留isOpn并在if块内添加isOpen = true。

标签: javascript jquery if-statement conditional-statements velocity.js


【解决方案1】:

因为每次isOpen = false; 因为你在click 中声明它。所以把它放在click event 外面如下:

$(function() {
   var isOpen = false; //this here
   $( "#navBar" ).click(function() {
      if (isOpen == false){
          $( this ).velocity({ height: 300});
          isOpen = true;
          console.log(isOpen);
          return false;
      }
      else{
          $( this ).velocity({ height: 50});
          isOpen = false;
          console.log(isOpen);
      }
   });
});

【讨论】:

    【解决方案2】:

    在点击处理程序外部声明isOpen,因为将其置于处理程序内部将使其始终为false

    var isOpen = false;
    
    $( "#navBar" ).click(function() {
    
          if (isOpen == false){
           $( this ).velocity({ height: 300});
              isOpen = true;
              console.log(isOpen);
              return false;
          }
          else{
           $( this ).velocity({ height: 50});
              isOpen = false;
              console.log(isOpen);
          }
    
       });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2021-10-30
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多