“if”语句对每次出现都执行相同的操作

时间:2017-07-09 18:58:05

标签: javascript jquery html css if-statement

在尝试为turn语句的每次运行切换if变量时,我会得到相同的结果。每次turn评估为2

以下是代码:

$(function() {
  var turn = 2;

  if (turn == 1) {
    $(".box").on("click", function() {
      var $thisBox = $(this).children();
      $thisBox.addClass("x").animate({
        opacity: 1
      }, 1000);
    });
    turn = 2;
  } else if (turn == 2) {
    $(".box").on("click", function() {
      var $thisBox = $(this).children();
      $thisBox.addClass("o").animate({
        opacity: 1
      }, 1000);
    });
    turn = 1;
  } else {
    document.write("Uh Oh");
  }
});

为什么会这样?

1 个答案:

答案 0 :(得分:2)

您只需设置onClick侦听器一次,并检查turn事件调用的函数内onClick值的值。

$(function() {
  var turn = 2;
  
  $(".box").on("click", function() {
    if (turn === 1) {
      console.log('foo');
      turn = 2;
    } else if (turn === 2) {
      console.log('bar');
      turn = 1;
    } else {
     console.log("Uh Oh");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'>Click me</div>

相关问题