通过jQuery向每个li元素添加一个不同的ID [英] Add a different ID to each li element by jQuery
本文介绍了通过jQuery向每个li元素添加一个不同的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的,我想问一个关于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>
我想为此<ul>
中显示的每个li添加一个不同的ID(例如<li class="something" id="li1">...
).有没有办法通过jQuery实现这一目标?
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?
非常感谢,雅库布(Jakub)
Thanks a lot, Jakub
推荐答案
从jQuery 1.4开始,您可以执行以下操作:
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));
});
...在1.4中也适用.我想这是偏爱的问题.
... which works in 1.4 as well. It's a matter of preference, I guess.
这篇关于通过jQuery向每个li元素添加一个不同的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文