Home » Jquery » javascript – Value not assigning in for function-Exceptionshub

javascript – Value not assigning in for function-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am running a for function which dynamically creates elements based on an entered number. I have an event listener for when the div is clicked.

This is the function that I am using to make these buttons.

function createGame(value) {
  previousNo = value;
  for (i = 0; i < value; i++) {
    gameCircle = document.createElement("div");
    gameCircle.className = 'gameCircle';
    gameCircle.id = "circle" + i;
    gameCircle.onclick = function() {
      checkGame(i);
    };
    document.getElementById("circleGame").appendChild(gameCircle);
  }
}

And this is the function I am calling.

function checkGame(j) {
  var nextNo = circleArr.shift();
  if (j == nextNo) {
    document.getElementById("circle" + i).style.backgroundColor = "#178a00";
  } else {
    console.log(j);
    getValueGame();
  }
}

Everytime the function runs, it returns six. Additionally, checking the onclick listener assigned says it runs this function.

function () {
  checkGame(i);
}

Why does the function return six on every button, and why is the i value not being assigned to the function?

How to&Answer:

It’s a question of chronology. Think about it; the event callback is not executed until later, by which time the value of i is, and has remained since the loop finished, a number equal to whatever value was.

The simplest way to resolve this is to use let for your iteration variable rather than var (this is good practice for variables these days in JavaScript generally, not just in your case.)

let “locks in” the value of i for each closure encountered in your loop. This answer discusses this in more detail.

You can achieve the same result by passing a var-declared iteration variable into the callback scope via an immediately-executed function expression (IIFE).

gameCircle.onclick = (i => () => checkGame(i))(i);

Or, in more readable terms:

gameCircle.onclick = (function(i) {
    return function() { checkGame(i); };
})(i)

Answer:

document.getElementById(“circle” + i).style.backgroundColor = “#178a00”;

i is not defined inside your function i think use j instead i