我有这个清单:
<ul>
<li class="level0">First item</li>
<li class="level1">Second item (children of level0)</li>
<li class="level2">Third</li>
<li class="level3">Forth</li>
<li class="level2">Third</li>
<li class="level3">Forth</li>
<li class="level4">Fifth</li>
<li class="level4">Fifth</li>
<li class="level2">Second</li>
<li class="level3">Third</li>
<li class="level2">Second</li>
</ul>
我希望在javascript或jQuery中使用此列表执行此操作
<ul>
<li class="level0">First item</li>
<ul>
<li class="level1">Second item (children of level0)</li>
<ul>
<li class="level2">Third</li>
<ul>
<li class="level3">Forth</li>
</ul>
<li class="level2">Third</li>
<ul>
<li class="level3">Forth</li>
<ul>
<li class="level4">Fifth</li>
<li class="level4">Fifth</li>
</ul>
</ul>
</ul>
<ul>
<li class="level2">Second</li>
<ul>
<li class="level3">Third</li>
</ul>
<li class="level2">Second</li>
</ul>
</ul>
</ul>
如果我能做到这一点,将极大地帮助用jQuery中的手风琴来显示它。
THX!
答案 0 :(得分:1)
试试这个:
var re = /\d+$/;
$( "ul li").detach().each( function() {
doit( this, +this.className.match(re)[0] );
});
function doit( li, level ) {
var cur = $( "ul:first"),
prev = cur,
ul;
while( level-- ) {
cur = $( "ul:first", cur );
if( !cur.length ) {
cur = $( "<ul>" ).appendTo(prev);
}
prev = cur;
}
cur.append(li);
}