For + slideToggle in Jquery does not work

1

Can anyone explain why my code does not work? I do not 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 thinking, I put a for that goes by, naming the class --- if i is 2 click_a2 will open 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><buttonclass="click_a1"> Detalhes </button>
        <div class="cola1" style="display:none" >
        hey!
        </div>

Note: I'll put a variable (instead of 1 ) that will add up everything this code rolls.

link

    
asked by anonymous 06.05.2015 / 20:34

1 answer

1

Your code does not work because this i is no longer the value you want when the click is called .

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

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

jsFiddle: link

You can also do this once you're using jQuery:

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

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

jsFiddle: link

    
06.05.2015 / 20:39