tags:

views:

14

answers:

3

Hey folks, diving into jQuery and loving it. I have a set of links ex:

<a href="#" title="Link 1" class="links">First Link</a>
<a href="#" title="Link 2" class="links">Second Link</a>

and also have a function that alerts the user what the link title is when they click on one:

$(".links").click(function(){
    var a_link = $(this);
    alert((a_link.attr("title"));
});

Now, how would I also alert the user what the next title in the associated class is? I tried using next() in a few formats but can't figure it out. Thanks a lot for the help.

+1  A: 

like this?

$(".links").click(function(){

    var a_link = $(this);
    alert(a_link.attr("title"));

    var a_next_link = a_link.next();
    alert(a_next_link.attr("title"));

});
Reigel
Ah, silliness. The problem was that I had something in between the two links, and my assumption was that next() would pull the next title within that class, not the next element.
Ryan
if you had something in between, then that would be the next element. ;)
Reigel
Yeah, that will do! No need to have it in the first place.
Ryan
A: 
$(".links").click(function(){
    var next = $(this).next().attr('title');
    alert(next || 'no adjacent element');
});​

Notice that if you click on the second link this will return undefined because there's no adjacent element to it.

Darin Dimitrov
A: 

As they both hold the same class that should work fine, jQuery automatically assigns the callback event to each item that has a class of links!

If you wish to know how to loop these yourself then you can go like so:

$('.links').each(function(){
    $(this).click(function(){
        /Blah
    });
});

if you wish to know about how to increment to the next element within the loop from the parent index you should try something like:

$(this).next().attr('title')

withinside the callback function, but you should do an if == undefined, because not all the time you would have that element, for instance when they click the last link, there will not be one after.

if you have other items on your page with the class links but you do not want to bind them then you can do

<div class="header_links">
    <a href="#1" title="Link 1" class="links">First Link</a>
    <a href="#2" title="Link 2" class="links">Second Link</a>
</div>
<a href="#3" title="Link 2" class="links">Second Link</a>

JavaScript:

$('.links','.header_links').each();

and this would only bind the links that are inside a div with a class of header_links

RobertPitt