There are many ways I could imagine a piece of code not working. Could you
be more specific about what didn't work? :-)

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

Or does it get there, but the value of "i" is not what you expect?

I know the code will have the latter problem, but I don't know if it's even
getting that far.

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.

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');
         });
     }

Now, every time you call the clicker() function, the code *inside* that
function has its own, unique "i" variable, whose value will be preserved as
long as your program runs. So even though the click event happens long after
the loop is completed, it will have the correct value.

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.

-Mike

> From: Girish Venkatachalam
> 
> Dear friends,
> 
> I am a newbie to jQuery and more so for javascript.
> 
> Please pardon my ignorance.
> 
> I am wondering why this code does not work.
> 
> for(i = 0; i < 10; i++) {
>       $('.treeview:eq(' +i+ ')').click(function() {
>               $('.monitor:eq(' +i+ ')').trigger('click');
>       });
> 
> }
> 
> Since this did not work I had to manually loop thro' them...
> 
> I also tried the variable approach.
> 
> var selector = '.treeview:eq(' +i+ ')';
>       $(selector)....
> 
> What is going on?
> 
> Many thanks in advance for the help.
> 
> -Girish
> 

Reply via email to