0

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......)  */
jaruesink
  • 1,205
  • 2
  • 14
  • 24

3 Answers3

1

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%'});
    });
});
Patrick Moore
  • 13,251
  • 5
  • 38
  • 63
  • this one works also, but I had to change the var j = 0 because it was skipping the first element for some reason – jaruesink Jun 25 '13 at 17:37
1

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%'});
 });
Community
  • 1
  • 1
J0HN
  • 26,063
  • 5
  • 54
  • 85
0

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?

jaruesink
  • 1,205
  • 2
  • 14
  • 24
  • Yes, using RegEx like that will make your code very unreadable. RegEx is not appropriate here. It will also perform worse than a `for` loop – Jonathan Jun 25 '13 at 17:42