Jquery selection problem
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 co开发者_如何学Gode:
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?
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();
}
精彩评论