tags:

views:

40

answers:

3

Hello, I'm trying to retrieve the hash value of the next link

HTML

<ul id="links">
    <li><a href="index.php?#1"></a></li>
    <li><a href="index.php?#2"></a></li>
    <li><a href="index.php?#3"></a></li>
</ul>

JS

$('#links li a').click(function() {

    var current_link = $(this).attr("href").substring(1);
    var next_link = $(this).next().attr("href").substring(1);

});

The current_link works, but I can't seem to retrieve the value of the link below. I think i'm missing an index() somewhere but i'm not exactly sure.

Thank you!

+2  A: 
$('#links li a').click(function(e) {
    e.preventDefault()
    var current_link = this.hash.slice(1);
    var next_link = '';
    if ($(this).parent().next().length > 0)
       next_link = $(this).parent().next().find('a')[0].hash.slice(1);

    alert('this: ' + current_link + ' next: ' + next_link);
    //return false;

});​

crazy demo

Reigel
Didn't know the native link had a `hash` property! Thanks! +1
alex
Thank you sir! You are both a gentleman and a scholar.
Ryan
One question: Does it make more sense to use substr(1) if I don't want the '#' in the string?
Ryan
@Ryan: `substring(1)` would give you `ndex.php?#1`. But you can use `hash.substring(1)`.
Felix Kling
@Ryan - you could use `.slice(1)` to erase the `#`. for example, `current_link.slice(1)` would return `1` if you click the first link.
Reigel
Thank you! I really appreciate the help. You guys are awesome.
Ryan
@Ryan - I updated my answer. It solves the problem when there's no next link. ;)
Reigel
Hrm, now i'm getting an "Unexpected Token ILLEGAL" when i drop this into my code.
Ryan
"Unexpected Token ILLEGAL" ?
Reigel
Uncaught SyntaxError: Unexpected token ILLEGAL in the (Chrome (Development Tools)) console
Ryan
does the demo I put above gave you that too ?
Reigel
I got it working.. Not sure what exactly was wrong :|
Ryan
Thanks for hanging in there.
Ryan
No problem. Glad I could help. ^_^
Reigel
A: 

You can use jQuery's .next() function to get the next sibling, for example, the next sibling of #1 would be #2.

Docs

http://api.jquery.com/next/

Example

http://jsfiddle.net/U7G6h/

Robert
A: 

Try this:

var next_link = $(this).parent().next().children('a').first().attr("href").substring(1);
Xint0