jQuery Created Nested List Based on Attribute
I get stuck when trying to implement recursive logic in jQuery--I don't have much practice with it. I have a simple need, which is to nest unsorted lists by class. What I have is two dynamic lists on a page (they're generated by two CAML queries).开发者_JAVA技巧 The first list will be the top level <li>
and the second list will be nested. The first list has <li>
s with numeric id's and the second list has <li>
s with numeric classes that match the id's that they have to be nested under. i.e.:
<ul>
<li id="10">Parent Item 1</li>
<li id="14">Parent Item 2</li>
</ul>
<ul>
<li class="10">Child 1</li>
<li class="10">Child 2</li>
<li class="14">Child X</li>
</ul>
There will be an undetermined number of parents and child <li>
s over time. Also, if it's better to use a different attr than class for the children that's fine. Ultimately I'll want to add more classes for CSS. Any help would be greatly appreciated.
Working example here: http://jsfiddle.net/rkCKT/
Assuming this markup:
<ul class="parents">
<li id="10">Parent Item 1</li>
<li id="14">Parent Item 2</li>
</ul>
<ul class="children">
<li class="10">Child 1</li>
<li class="10">Child 2</li>
<li class="14">Child X</li>
</ul>
this would work:
$(document).ready(function(){
$('ul.children li').each(function(){
probable_parent = $('ul.parents li#' + $(this).attr('class'));
if (probable_parent.length)
{
if (!probable_parent.find('ul').length) probable_parent.append('<ul/>');
$(this).detach().appendTo(probable_parent.find('ul'));
}
});
});
Edit:
As soon as you add any classes to the .children li
s for presentational reasons, everything will be broken.
For this and half a million other reasons, if your document is HTML5, I strongly suggest using proper attributes for the parent-child relationship. Ideally, the markup would look something like this:
<ul class="parents">
<li data-itemid="10">Parent Item 1</li>
<li data-itemid="14">Parent Item 2</li>
</ul>
<ul class="children">
<li data-itemid="10">Child 1</li>
<li data-itemid="10">Child 2</li>
<li data-itemid="14">Child X</li>
</ul>
精彩评论