jaruesink
jaruesink

Reputation: 1203

Loops in jquery selectors

So this should be a very simple loop, but it's not working for me.

    for(var j = 1, len = $('#account .person').length; j <= len; j++) {

    $('#a' + j).click( function(){ 
        $('#account' + j).css({left:'0%'});
    });

    };

I was hoping this would spit out....

  $('#a1').click( function(){
      $('#account1').css({left:'0%'});
  });
 $('#a2').click( function(){
      $('#account2').css({left:'0%'});
  });
/* (etc......)  */

Upvotes: 0

Views: 68

Answers (3)

jaruesink
jaruesink

Reputation: 1203

Someone added this as an answer and then deleted it for some reason, but it works for me.

$('[id^="a"]').click( function(){
 $('#account'+this.id.match(/(\d+)$/)[0]).css({left:'0%'});
});

Is there some reason I shouldn't use this method?

Upvotes: 0

J0HN
J0HN

Reputation: 26961

The function in

$('#a' + j).click( function(){ 
    $('#account' + j).css({left:'0%'});
});

creates a closure. In short, js interpreter keeps local variables alive even after the block finishes, but it does not copy it. So, by the time click event happends, the for block is already finished, and the value of j left as it was for the final iteration.

In order to avoid that, determine the j in the function from what you have, namely, the element you are attaching the handler, like this (warning: not tested):

 $('#a' + j).click( function(){ 
    var correct_j = $(this).attr('id').replace('a','');
    $('#account' + correct_j ).css({left:'0%'});
 });

Upvotes: 1

Patrick Moore
Patrick Moore

Reputation: 13354

If you're making the same change to every element, and each of your #a__ elements are in fact the same as .person class elements, you can simply do:

$("#account .person").css({left: '0%' } );

No need to loop through. If they are not related, and you need the loop, use .each() as stated in the comments:

var j =1;
$("#account .person").each( function(){
    j++;
    $('#a' + j).data( 'num', j );
    $('#a' + j).click( function(){ 
        $('#account' + $(this).data('num') ).css({left:'0%'});
    });
});

Upvotes: 1

Related Questions