For + slideToggle in Jquery does not work

Asked

Viewed 58 times

1

Can anyone explain why my code doesn’t work? I don’t know exactly how many divs will generate, but the maximum is 25.

So I wanted each click button to specifically open the div "glue" attached to it.

In my mind, I put a for that goes along, naming the class --- if i is 2nd the click_a2 will open the cola2 and so on.

jQuery and HTML:

    for (i = 0; i < 25; i++) {
            $('.click_a'+i).click(function () {
                    $('.cola'+i).slideToggle();
            });
        };
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click_a1"> Detalhes </button>
        <div class="cola1" style="display:none" >
        hey!
        </div>

Note: Understand that I will put a variable (instead of the 1) that will add up everything that code runs.

https://jsfiddle.net/rgLjpb7s/

1 answer

1


Your code doesn’t work because that i no longer has the value you want it to have when the click is called.

If you create a new scope it already works, so the value of the variable is stored within this scope:

for (i = 0; i < 25; i++) {
    (function (i) {
        $('.click_a' + i).click(function () {
            $('.cola' + i).slideToggle();
        });
    })(i)
};

jsFiddle: https://jsfiddle.net/rgLjpb7s/1/

You can also do so once you are using jQuery:

$('[class^=click_a').each(function (i) {
    (function () {
        var nr = i + 1;
        var cola = $('.cola' + nr);
        $(this).click(function () {
            cola.slideToggle();
        });
    })();
});

has 2 advantages: works for n number of .click_a, another is that it caches the element that caches the slide, improving the performance a little.

jsFiddle: https://jsfiddle.net/rgLjpb7s/3/

  • 1

    Thank you very much, I will have to study a little more to understand why this happens. I thought the variable would continue the same value since it does not leave the for. Anyway, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.