> > From: Michael Geary
> > But is the loop index that useful here? I'm trying to 
> > picture what you might do with it. There may be a
> > better way to do this - if you could say more about
> > your application, someone may have a suggestion.

> From: SLR
> To give you a brief rundown. Imagine having a generic 
> function with a nested switch statment.
> 
> function myFunction(param)
> {
>    switch(param)
>    {
>       case 1: // some code
>       break;
> 
>       case 2: // some code
>       break;
> 
>       case 3: // some code
>       break;
>    }
> }
> 
> Now, imagine you have the following html items
> 
> <div id="myLinks">
>    <a href="#">link 1</a>
>    <a href="#">link 2</a>
>    <a href="#">link 3</a>
> </div>
> 
> Basically, I want to do is have jQuery make each link call 
> myFunction when clicked and pass its index so the the correct 
> switch statement is fired...

That will work, but it's a fairly brittle way to do things. If you add
another link earlier in your page, it will change the loop indexes and
you'll have to revise your code to match.

Instead, I would suggest giving each of those A tags its own ID. That way
you don't have to change your code if you rearrange the tags or add another
one in the middle. For example:

 <div id="myLinks">
    <a href="#" id="one">link 1</a>
    <a href="#" id="two">link 2</a>
    <a href="#" id="three">link 3</a>
 </div>

Now you can simply give each one its own click handler:

 $('#one').click( function() {
    // handle click on link 1
    return false;  // suppress default action
 });

 $('#two').click( function() {
    // handle click on link 2
    return false;  // suppress default action
 });

etc.

Or you can still use a switch statement if you want:

 $('a').click( function() {
    switch( this.id ) {
       case 'one':
          // handle click on link 1
          break;
    }
 });

If there are a large number of A tags in your page, you may want to consider
event delegation instead. It's pretty easy to do. How many A tags will there
be?

-Mike

Reply via email to