Home > Back-end >  Force JavaScript to wait for a click (loops)
Force JavaScript to wait for a click (loops)

Time:07-15

I have 4 buttons different colors and I want to check my clicks against the given array.

What I'm expecting:is giving me the result of my click each time and with "i" increasing each time.

instead:Im getting 15*times the answer. with "i" printing 15 times as "15", instead of 1>2>3>4>5>6....

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

CodePudding user response:

Your code is adding 15 event handlers for the buttons. Try using one event handler, incrementing i and using an if statement to make sure i is under 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  id="blue">B</button>
<button  id="green">G</button>
<button  id="yellow">Y</button>
<button  id="red">R</button>

  • Related