0

我想弄清楚这一点,我正在尝试构建一个具有多级的简单菜单树

RootFolder
- First Sub Folder
-- First Sub Sub Folder
--- First Sub Sub Sub Folder
--- First Sub Sub Sub Sub Folder
- Second Sub Folder
- Second Sub Sub Folder

我的 XML 非常简单(不是正确的值)

<OrgFolderDetails>
    <FolderName>Main Folder</FolderName>
    <TheChildren>
        <OrgFolderDetails>
            <FolderName>First Sub Folder</FolderName>
            <TheChildren>
                <OrgFolderDetails>
                    <FolderName>First Sub Sub Folder</FolderName>
                    <TheChildren>
                        <OrgFolderDetails>
                            <FolderName>First Sub Siub Sub Folder</FolderName>
                            <TheChildren>
                                <OrgFolderDetails>
                                    <FolderName>First Sub Sub Sub Sub Folder</FolderName>
                                    <TheChildren/>
                                </OrgFolderDetails>
                            </TheChildren>
                        </OrgFolderDetails>
                    </TheChildren>
                </OrgFolderDetails>
            </TheChildren>
        </OrgFolderDetails>
        <OrgFolderDetails>
            <FolderName>Second Sub Folder</FolderName>
            <TheChildren>
                <OrgFolderDetails>
                    <FolderName>Second Sub Sub Folder</FolderName>
                    <TheChildren/>
                </OrgFolderDetails>
            </TheChildren>
        </OrgFolderDetails>
    </TheChildren>
</OrgFolderDetails>

我使用了 jQuery 的 .filter() 和。find() each() 没有任何成功,它没有给我漂亮的破折号来指示我在哪个级别,它只是吐出文件夹名称。

我的代码遍历

 $(data).find("FolderName").each(function(){
             var folderName = $(this).text();

            $("#folderLevels").append(folderName+"<br/>");
         });
4

2 回答 2

1

好的,据我了解,我们需要构建一个菜单,前面有一定数量的破折号,具体取决于孩子的水平。幸运的是,jQuery 让这变得很容易。

$(data).find("FolderName").each(function(){ 
    var levels = $(this).parents("OrgFolderDetails").size();
    var text = $(this).text();
    var html = "";

    for(var j=0; j < levels; j++){
        html += "-";    
    }
    html += " "+text+"</br>"; //add in that space after the dashes, and the <br>

    $("#folderLevels").append(html);
});

希望有帮助。主要的助手是parents()方法。 http://api.jquery.com/parents

于 2012-05-23T03:21:46.690 回答
0

我想你会想要为此使用递归函数。

var s = getNestedString($(data), 0);

function getNestedString(d, level) {
    // get the name of current node
    var s = d.children("FolderName").text() + "<br/>";

    // prepend with dashes for inner levels
    for (var i=0 ; i<level ; i++) {
        s = "-" + s;
    }

    // get children and call this function recursively (incrementing level)
    var ch = d.children("TheChildren").children("OrgFolderDetails");
    for (var i=0 ; i < ch.length ; i++) {
        s = s + getNestedString(ch[i], level+1);
    }

    // return string for current and nested nodes
    return s;
}
于 2012-05-23T03:22:14.923 回答