0

There is such a piece where how

$(document).on('click', '#calcA', function() {
    $("#calcASum").addClass("field");
    ($(this).is(":checked")) ? $("#calcAInfo").css("display", "") : $("#calcAInfo").css("display", "none");
});

$(document).on('click', '#calcB', function() {
    $("#calcBSum").addClass("field");
    ($(this).is(":checked")) ? $("#calcBInfo").css("display", "") : $("#calcBInfo").css("display", "none");
});

$(document).on('click', '#calcC', function() {
    $("#calcCSum").addClass("field");
    ($(this).is(":checked")) ? $("#calcCInfo").css("display", "") : $("#calcCInfo").css("display", "none");
});

only AB and C changes; I wanted to write through for ()

var item = ['A', 'B', 'C'];
for(var i=0; i<item.length; i++) {
    $(document).on('click', '#calc'+item[i], function() {
        $("#calc"+item[i]+"Sum").addClass("field");
        ($(this).is(":checked")) ? $("#calc"+item[i]+"Info").css("display", "") : $("#calc"+item[i]+"Info").css("display", "none");
    });
}

he adds one more function after the click function. It turns out inside the function already i = 3. There are other solutions to this problem? thanx

1 Answers1

1

The fact is that you are referencing an outer scoped variable.

You can have a look at this question: Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. What is wrong?

And in your case you can try this code :

var item = ['A', 'B', 'C'];
for(var i=0; i<item.length; i++) {
    const j = i;
    $(document).on('click', '#calc'+item[j], function() {
        $("#calc"+item[j]+"Sum").addClass("field");
        ($(this).is(":checked")) ? $("#calc"+item[j]+"Info").css("display", "") : $("#calc"+item[j]+"Info").css("display", "none");
    });
}
Bertrand
  • 26
  • 1
  • It's not so much that it's an "outer scoped variable" - it's that the click event occurs *after* the for loop has completed, so the value of `i` has already changed by the time you click. Have a good read of this: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – freedomn-m Nov 15 '18 at 08:54