Add a different ID to each li element by jQuery

对着背影说爱祢 提交于 2019-12-30 06:07:08

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/2847561/add-a-different-id-to-each-li-element-by-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!