[英]Jquery - Auto Increment ID's for Nested List
I have a nested list that resembles this:我有一个类似于这样的嵌套列表:
<div id="treeview-left">
<ul>
<li>Country
<ul>
<li>Region
<ul>
<li>District
<ul>
<li>Group
<ul>
<li>People</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
This list is dynamically generated, and I need to auto increment ID's for each list item at each level.这个列表是动态生成的,我需要为每个级别的每个列表项自动增加 ID。
Eg.例如。 Country li's would have #Lv1-1 , #Lv1-2, #Lv1-3 Region li's would have #Lv2-1 , #Lv2-2, #Lv2-3国家 li 有 #Lv1-1 , #Lv1-2, #Lv1-3 地区 li 有 #Lv2-1 , #Lv2-2, #Lv2-3
Each level needs to start with at 0 or 1, and increment the id based on it's index in that specific ul.每个级别都需要从 0 或 1 开始,并根据它在该特定 ul 中的索引来增加 id。
This is my current code, I am unable to even get the first level working.这是我当前的代码,我什至无法使第一级工作。
<script>
$(function () {
$("#treeview-left > ul li").each(function () {
var TopPosition = $(this).index();
console.log(TopPosition);
$(this).id("Lvl1"+TopPosition);
});
});
</script>
Your help is appreciated.感谢您的帮助。
Thanks谢谢
$(function () {
$("#treeview-left ul").each(function (i, item) {
var Tp = i + 1;
$(this).find('li').each(function (j, item) {
$(this).attr('id', "Lvl" + Tp + '-' + (j + 1));
});
});
});
here is a Recursive solution这是一个递归解决方案
function updateIds($node, index) {
if ($node.is('ul')) {
updateIds($node.children(), index);
} else {
$node.each(function (i, el) {
$(el).attr('id', 'Lv' + index + '-' + (i+1));
var $child = $node.children('ul');
if ($child.length > 0) {
updateIds($child, index+1);
}
});
}
}
demo: http://jsfiddle.net/3xpBw/1/演示: http : //jsfiddle.net/3xpBw/1/
Another solution could be: Fiddle另一种解决方案可能是:小提琴
<script type="text/javascript">
$(function () {
var count=0
$('ul').each(function(i, ul) {
count++
ul = $(ul);
var first=count
ul.children('li').each(function(i, li) {
li = $(li);
var second = first + '.' + (li.index() + 1);
li.prepend('<span>' + second + '</span>');
li.attr('id',second)
})
})
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.