Sunday, November 30, 2008

[jQuery] Re: jQuery loop help

One way you could do this is have give the links in question a specific ID,
class or attribute.

For example:

<div id="myLinks">
<a href="#" id="link1">link 1</a>
<a href="#" id="link2">link 2</a>
<a href="#" id="link3">link 3</a>
</div>

$('#myLinks a').click(doSomething);

function doSomething(e){
switch ($(this).attr('id'))
{
case "link1":
// Some code.
break;
case "link2":
// Some code.
Break;
case "link3":
// Some code.
break;
}
}

JK
-----Original Message-----
From: jquery-en@googlegroups.com [mailto:jquery-en@googlegroups.com] On
Behalf Of SLR
Sent: Sunday, November 30, 2008 3:12 PM
To: jQuery (English)
Subject: [jQuery] Re: jQuery loop help


> No question is too "noobie". Welcome aboard! :-)

I appreciate the warm welcome = )

> That code won't work at all.
> I would suggest reading the doc page on .each():

Definitely on my to-do list...

> If you just want the loop index, it's passed to the .each() callback as
the
> first parameter:
>
>     $('a').each( function( i ){
>         // 'i' is the loop index
>         $(this).click(function(){
>             // You can use 'i' directly in this code
>         });
>     });

Thanks for the info here, I'll definitely play around with it and see
what I can do.

> 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.

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...

No comments: