If you put the loop inside a function, you'll have access to the 'i'
variable because of scoping:

// *** just for demonstration, this is bizarre ***
for (var i=0; i < TAGS.length; i++) {
  (function(i){
        TAGS[i].click( function(event) {
                alert(B[i]);
        });
  })(i);
};

You can achieve that using jQuery.each:

$.each(TAGS, function(i, $v){
   $v.click(function(){
      alert( B[i] );
   });
});

But how about a simpler approach? This way you can better relate
selectors to their corresponding values:

var behaviours = {
   '.class': "hey",
   '#foo': "oh"
};

$.each(behaviours, function(sel, value){
   $(sel).click(function(){
      alert( value );
   });
});

On Jun 30, 10:30 pm, Olivier <the.fuz...@gmail.com> wrote:
> Hi,
>
> I'm trying to to something in javascript but I don't know how to do
> that.
>
> Basicly, I have something like this :
> TAGS = new Array(
>         $(".class"),
>         $("#foo")
> );
>
> B = new Array(
>         "hey",
>         "oh"
> );
>
> for (var i=0; i < TAGS.length; i++) {
>         TAGS[i].click( function(event) {
>                 alert(B[i]);
>         });
>
> }
>
> I would like to alert "hey" when the user clicks on a tag of class
> "class" and to alert "oh" when he clicks on a tag of id "foo".
> This doesn't work because B[i] takes the "i" when the callback
> function is called by jquery (when a click occurs). So it always takes
> B[2] in this case (which doesn't exist).
> How could I effectively alert B[0] for .class tags and B[1] for #foo
> tags ?
>
> Thanks,
> Olivier

Reply via email to