开发者

Add a different ID to each li element by jQuery

I'm new here and I'd like to ask a question about jQuery.

I have the unordered list like:

<ul id="pages">
    <li class="something"><a href="#"></a></li>
    <li class="something"><a href="#"></a></li>
    <li class="something"><a href="#"></a></开发者_如何转开发li>
</ul>

And I'd like to add a different ID to every li displayed in this <ul> (eg. <li class="something" id="li1">...). Is there a way how to achieve this via jQuery?

Thanks a lot, Jakub


As of jQuery 1.4, you can do this:

$('#pages li').attr('id', function(i) {
   return 'page'+(i+1);
});

In earlier versions, you'd need to write:

$('#pages li').each(function(i) {
    $(this).attr('id', 'page'+(i+1));
});

... which works in 1.4 as well. It's a matter of preference, I guess.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜