On 22:12:19 Oct 22, Michael Geary wrote:
> 
> There are many ways I could imagine a piece of code not working. Could you
> be more specific about what didn't work? :-)
> 

I did not want to be verbose. Your analysis is correct. I did not get
the value I expected. I was getting the last value as reasoned by you.

> Does it get into your click function at all? What happens if you put an
> alert() inside the click function, before the .monitor code?
> 

It works but the value of i is wrong.

> Or does it get there, but the value of "i" is not what you expect?
> 
> Why would "i" have the wrong value? This code has a single variable "i". The
> variable starts with a value of 0, and after the "for" loop completes, the
> value of "i" is 10.
> 
> When you click one of your items, the code will use the *current* value of
> "i", which is 10.

But that is not what I would expect. ;)

> You could fix it by introducing a function:
> 
>     for(i = 0; i < 10; i++)
>         clicker( i );
> 
>      function clicker( i ) {
>          $('.treeview:eq(' +i+ ')').click(function() {
>              $('.monitor:eq(' +i+ ')').trigger('click');
>          });
>      }
> 

Does it involved the scary javascript closure concept? ;)

 
> Or you could let jQuery do some of the work for you, like this:
> 
>     $('.treeview:lt(10)').each( function( i ) {
>         $(this).click(function() {
>              $('.monitor:eq(' +i+ ')').trigger('click');
>          });
>      });
> 
> If you don't really need the limit of 10, you can omit the :lt(10) in the
> first line.

I actually replaced my long code with this piece of beauty. ;)

     $('.treeview').each( function( i ) {
         $(this).click(function() {
              $('.monitor:eq(' +i+ ')').trigger('click');
          });
      });

And it works like a charm. ;)

Many thanks Mike.

Ever learning.

-Girish

Reply via email to