开发者

Append index to href

I have an unordered list of links that I need to append the index as a number to.

So href="#" reads href="#1", href="#2" etc.

I understand I probably need to use .each() but my syntax-fu isn't up to scratch yet.

Part of me knows this is ridiculously simple but I'm having a m开发者_如何学JAVAonday atm.


Do you mean the index of the element in the set of selected elements? If so you can use .attr() and pass a function to it:

$('a').attr('href', function(i, value) {
    return value + (i+1);
});

Of course you have to select only those links you want, e.g. by giving your list an ID:

$('#theList a')

Update:

There seems to be a bug in jQuery 1.3.2 (and before). It seems the old value is not passed to the callback. So you would have to read the value explicitly:

return this.href + (i+1);

Of course if the old value is always # then you can just concatenate it with the index:

return '#' + (i+1); 

But in this case, you could use each() in this case, as @Shadow Wizard shows in his answer. The advantage of passing a function to attr is only that you avoid two access to the attribute (one to read and one to write), which does not seems to work in jQuery 1.3.2 anyway.


Well, it's Sunday but..

$("#myList li").each(function(index) {
    $(this).find("a").attr("href", "#" + (index + 1));
});

Live test case.


Easier to use the .attr() function.

$('ul a').attr("href", function(index, cHRef) {
    return cHRef + index;
});

If you are restricted to older jQuery implementations older than v1.1, then you will need to use .each():

$('ul a').each(function(index, cAnchor) {
    cAnchor.attr('href', cAnchor.attr('href') + index);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜