0

Ok, Simply... I want to make this (which works perfectly, but is obviously too much writings when i have #b up to #b20):

$("#b" + 1).click(function () {
    $('.c').hide();
    $(".a" + 1).show();
});
$("#b" + 2).click(function () {
    $('.c').hide();
    $(".a" + 1).show();
});

Simple, like this:

for (var i = 0; i < 50; i += 1) {
    $("#b" + i).click(function () {
        $('.c').hide();
        $(".a" + i).show();
        alert('Hey'+i);
    });
}

$("#b" + i) is button on htmlpage, and $(".a" + i) is the text which is supposed to be viewed on the page by clicking on the button. //So the text is with class="c a1", class="c a2", ...; and the button is with id="#b1", id="#b2"... But when I execute the code (Click on #b1, #b2, or...), .c hides (as expected), and the next step is only executed for i=50 (proved with the alert).

Any ideas?

P. Frank
  • 5,691
  • 6
  • 22
  • 50
  • b starts at 0, do you want that? in your first line you say you just have #b with no number. please clarify. – ergonaut Oct 16 '15 at 13:37
  • A maybe cleaner approach would be to just give all buttons the same class (i.e. "btn") and then a `data-num` attribute with the actual number. Then you can just say `$(".btn").click(function() { var i = $(this).data("num"); /* rest of code */ });`. – basilikum Oct 16 '15 at 13:46

1 Answers1

0

Try this in the for loop:

for (var i = 0; i < 50; i += 1) {
    (function (j) {
        $("#b" + j).click(function () {
            $('.c').hide();
            $(".a" + j).show();
            alert('Hey'+j);
        });
    }(i))
}

Actually, this is a classic, you should read more about closures and about the fact that JS is a 'pass as value' language. But simply put:

The anonymous function sent as argument to the click function has a reference to the environment it was created in, and as so, has a reference to the i variable, which is precisely the same for every function created (one function is created at each iteration). So every anonymous function will have i with the last value of the loop.

By using another closure, you use the fact that JS passes argument as value, and not as reference: the j (even if you call it i, as I previously had) is not a reference to the i, but rather the value of i at the time it is passed to the function.

laruiss
  • 3,780
  • 1
  • 18
  • 29
  • Ok. I'm sorry that there's a duplication with another question. And thank you //for I fought with this question for 3 days//. – Ruth Busari Oct 18 '15 at 13:53