0

Can someone please tell me why when I click on the [s] href created next to the list of names (myhand) generated it always says selection and i are 5?

var printDD = function(myhand, mydiv){
    var dtext = "";
    for(var i = 0;  i < myhand.length; i++){
        dtext += '<a href="#" id="dd'+i+'">[s]</a>' + myhand[i] + ', ';
    }

    mydiv.html(dtext);

    for(var i = 0;  i < myhand.length; i++){
        $('#dd'+i).click(function(){
        selection = i;
        console.log("sel: " + selection + " i: " + i);
        });
    }
}
CyanPrime
  • 5,096
  • 12
  • 58
  • 79

2 Answers2

1

You want to take a look at JavaScript closure inside loops – simple practical example. As the answer to that question says, you can create a function to return one, or you can use inline function invocation in the for loop like so:

for(var i = 0;  i < myhand.length; i++) {
    $('#dd'+i).click((function(x) {
        return function () {
            selection = x;
            console.log("sel: " + selection + " x: " + x);
        }
    }(i)));
}
Community
  • 1
  • 1
JamieJag
  • 1,541
  • 2
  • 11
  • 18
0

Because the value of i is determined at the time the click handler is run. So it will always have the value of myhand.length - 1, which is the state you left i in after the for-loop.

nfechner
  • 17,295
  • 7
  • 45
  • 64