views:

37

answers:

1

Hi Guys,

I have a bunch of elements with ids like "check1", "check2", "check3" etc. I want to loop through each of them and hide them and set onclick funcion. Here is my current code:

for (i = 0; i < badgeArray.length; i++) {
        jQuery("a#check"+ i + "").click(function(){
            jQuery("#check" + i + "info").toggle();
            jQuery("a#check"+ i + "").toggleClass("extrasopen");
            jQuery("a#check"+ i + "").toggleClass("extrasclosed");
        });
        jQuery("#check" + i + "info").hide();
    }   

All "#check" + i + "info" elements are hidden, but hide/display functionality doesn't work. When I try it just for one element like this:

jQuery("a#check1").click(function(){
    jQuery("#check1info").toggle();
    jQuery("a#check1").toggleClass("extrasopen");
    jQuery("a#check1").toggleClass("extrasclosed");
}); 

It works.

Any ideas?

+2  A: 

You need to use a closure:

for (var i = 0; i < badgeArray.length; i++) {
    (function(i) {
        jQuery("a#check"+ i).click(function(){
            jQuery("#check" + i + "info").toggle();
            jQuery("a#check"+ i).toggleClass("extrasopen").toggleClass("extrasclosed");
        });
        jQuery("#check" + i + "info").hide();
    })(i);
}

But you could also use the contextual element and its properties:

for (var i = 0; i < badgeArray.length; i++) {
    jQuery("a#check"+ i).click(function(){
        jQuery("#" + this.id + "info").toggle();
        jQuery(this).toggleClass("extrasopen").toggleClass("extrasclosed");
    });
    jQuery("#check" + i + "info").hide();
}
Gumbo
That's it. Thx a lot.
Mladen