0

I'm try to add click event on a Jquery Element using variable "element"..

but the variable into each Event change when I change this variable outside the "click"

Fiddle

like that:

$(document).ready(function () {
    var counto = 5;
    for (i = 1; i <= counto; i++) {
        $('.link.' + i).click(function (event) {
            event.preventDefault();
            $('div.output').html(i);
        });
    }
});

sorry for my worse english :-)

Thank You

palaѕн
  • 72,112
  • 17
  • 116
  • 136
Jean-philippe Emond
  • 1,619
  • 2
  • 17
  • 29

1 Answers1

1

You have to include the script inside a scope:

$(document).ready(function () {
    var counto = 5;
    for (var i = 1; i <= counto; i++) { // do not omit the keyword var
        (function (n) {
            $('.link.' + n).click(function (event) {
                event.preventDefault();
                $('div.output').html(n);
            });
        })(i);
    }
});

Otherwise the click function will use the i variable when it's assigned to the last value of the loop(in this case 6).

Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
  • The solution is correct, but not the explanation. The event handler already *is* a closure and that is what is causing the problem. The solution is to create a new scope by executing a function, not by using a "closure" (closures don't create scope). – Felix Kling Jun 14 '13 at 17:12