代码之家  ›  专栏  ›  技术社区  ›  cyka

强制JavaScript等待单击(循环)

  •  0
  • cyka  · 技术社区  · 2 年前

    我有4个不同颜色的按钮,我想根据给定的数组检查我的点击。

    :每次都会给我单击的结果,并且每次“i”都会增加。

    var arrColor = ['blue', 'yellow', 'green', 'red', 'blue', 'blue', 'yellow', 'blue', 'blue', 'yellow', 'yellow', 'green', 'green', 'blue', 'yellow'];
    
    var i = 0;
    for (var i = 0; i < 15; i++) {
        $(".btn").click(function (event) {
            console.log(i); // check on i
            if (arrColor[i] === event.target.id) {
                console.log("great");
            }
            else {
                console.log("Wrong");
            }
        });
    
    }
    

    enter image description here

    1 回复  |  直到 2 年前
        1
  •  2
  •   imvain2    2 年前

    您的代码为按钮添加了15个事件处理程序。尝试使用一个事件处理程序,递增i,并使用if语句确保i小于15。

    var arrColor = ['blue', 'yellow', 'green', 'red', 'blue', 'blue', 'yellow', 'blue', 'blue', 'yellow', 'yellow', 'green', 'green', 'blue', 'yellow'];
    
    let i = 0;
    
    $(document).on("click", ".btn", function() {
      if (i <= 15) {
        if ($(this).attr("id") == arrColor[i]) {
          console.log("great");
        } else {
          console.log("wrong");
        }
        i++;
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button class="btn" id="blue">B</button>
    <button class="btn" id="green">G</button>
    <button class="btn" id="yellow">Y</button>
    <button class="btn" id="red">R</button>