如何在ul列表中获取父子关系的jQuery中的树结构?

时间:2014-04-02 08:17:39

标签: jquery

<ul>
<li parent-id="0" li-id="16">Anthropology Department</li>
<li parent-id="16" li-id="18">Anthropology Faculty Collections</li>
<li parent-id="16" li-id="23">Shared Collections</li>
<li parent-id="0" li-id="19">Center for Research on Vermont</li>
<li parent-id="19" li-id="24">Collections for Testing</li>
<li parent-id="24" li-id="25">Geology Department</li>

//我想要这样

<ul>
<li parent-id="0" li-id="16">Anthropology Department
    <ul>
        <li parent-id="16" li-id="18">Anthropology Faculty Collections</li>
        <li parent-id="16" li-id="23">Shared Collections</li>
    </ul>
</li>
<li parent-id="0" li-id="19">Center for Research on Vermont
    <ul>
        <li parent-id="19" li-id="24">Collections for Testing
            <ul>
               <li parent-id="24" li-id="25">Geology Department
                </li> 
            </ul>
        </li>
    </ul>
</li>

我想将li-id与parent-id匹配,然后如果匹配的parent-id列表应该附加到li-id列表。

到目前为止我已经尝试过了:

var liid = $('li').attr('li-id');
var parid = $('li').attr('parent-id');
if(liid==parid){
parid.appendTo(liid)
}

3 个答案:

答案 0 :(得分:2)

尝试

jQuery(function($){
    var $ul = $('ul');
    $ul.find('li[parent-id]').each(function () {
        $ul.find('li[parent-id=' + $(this).attr('li-id') + ']').wrapAll('<ul />').parent().appendTo(this)
    });
})

演示:Fiddle

答案 1 :(得分:2)

尝试

$("li").each(function(){
 var ul=$("<ul/>");
 ul.append($("[parent-id="+$(this).attr("li-id")+"]"));
 $(this).append(ul);

});

Demo

答案 2 :(得分:0)

    $("li").each(function () {
    var lid = $(this).attr("li-id");
    var pid = $(this).attr("parent-id");
    var li = $(this);
    if (pid != 0) {
       // alert(pid);
        var theli = $("li").filter("[li-id='" + pid + "']");
        if (theli.find("ul").length > 0) {
            theli.find("ul").append("<li parent-id='" + pid + "' li-id='" + lid + "'>" + li.html() + "</li>");
        } else {
            theli.html("<ul></ul>");
            theli.find("ul").append("<li parent-id='" + pid + "' li-id='" + lid + "'>" + li.html() + "</li>");

        }
        li.remove();
    }
});

试试这段代码, jsfiddle url:http://jsfiddle.net/mukuljp/Nvguw/