我有一个无序列表,需要拆分为分层列表,具体取决于已预先分配给每个的类
<ul>
<li class="level-1"><a href="#">First Level Item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-1"><a href="#">Next First Level Item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
</ul>
我需要它成为基于每个 li 的类的嵌套列表,因此最终列表呈现为:
<ul>
<li class="level-1"><a href="#">First Level Item</a>
<ul>
<li class="level-2"><a href="#">Second Level item</a>
<ul>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
</ul>
</li>
<li class="level-2"><a href="#">Second Level item</a>
<ul>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
</ul>
</li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
</ul>
</li>
<li class="level-1"><a href="#">Next First Level Item</a>
<ul>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a>
<ul>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
</ul>
</li>
</ul>
</ul>
因为我不能在输出这个列表的 CMS 上运行服务器端代码,所以我必须在客户端重新组织这个 HTML 列表。
我花了很多时间尝试编写自己的 jQuery 来创建新的层次结构,但运气不佳。我的第一次尝试是尝试使用 jQuery .before</ul></li>
在类之前添加附加标签,然后在标签之后附加一个新<ul>
标签,但我无法<ul> <li>
插入任何标签——似乎 jquery 会添加一个<p>
等但是不是</ul></li>
吗?
然后我尝试使用 .wrap<ul></ul>
在需要的地方放置一个新的,但我还不够聪明,无法弄清楚如何选择和分组所有子或孙子来包装。
有人对我应该尝试做什么有任何提示吗?