views:

27

answers:

2
$('ul li a').each(function(index, element){$(element).attr("href", "#img"+index);});

I'd like my list item links to start with the href as "#img1" and count up from there for each item. The code I have will start at "#img0" which doesn't work for what I'm trying to accomplish.

Thanks for any help.

A: 

Try:

$('ul li a').each(function(index, element){$(element).attr("href", "#img"+(index+1));});

Justin808
+3  A: 

Since jQuery 1.4+, .attr() takes a function directly, like this:

$('ul li a').attr("href", function(index) { return "#img" + (index+1); });

The index is still 0 based, so just add 1 when using it.

Nick Craver
Nick - According to the docs, `.attr()` has accepted a function since `jQuery 1.1`. (The 1.4 release notes attest to the fact as well.) I often forget that it is the odd one out of the bunch. :o) *EDIT: I think the second parameter was added in 1.4 though.*
patrick dw
@patrick - It got an overhaul in 1.4 mainly to support all the other function methods...it had a few issues before then with `href` (relative vs absolute, in you guessed it: IE) :)
Nick Craver
Nick - Ah, I see.
patrick dw