根据菜单项的URL路径结构创建嵌套的UL菜单

时间:2011-08-20 18:09:49

标签: javascript jquery arrays url html-lists

我有一系列菜单项,每个菜单项都包含名称和URL,如下所示:

var menuItems = [  
    {  
        name : "Store",  
        url : "/store"  
    },  
    {  
        name : "Travel",  
        url : "/store/travel"  
    },  
    {  
        name : "Gardening",  
        url : "/store/gardening"  
    },  
    {  
        name : "Healthy Eating",  
        url : "/store/healthy-eating"  
    },  
    {  
        name : "Cook Books",  
        url : "/store/healthy-eating/cook-books"  
    },  
    {  
        name : "Single Meal Gifts",  
        url : "/store/healthy-eating/single-meal-gifts"  
    },  
    {  
        name : "Outdoor Recreation",  
        url : "/store/outdoor-recreation"  
    },  
    {  
        name : "Hiking",  
        url : "/store/outdoor-recreation/hiking"  
    },  
    {  
        name : "Snowshoeing",  
        url : "/store/outdoor-recreation/hiking/snowshoeing"  
    },  
    {  
        name : "Skiing",  
        url : "/store/outdoor-recreation/skiing"  
    },  
    {  
        name : "Physical Fitness",  
        url : "/store/physical-fitness"  
    },  
    {  
        name : "Provident Living",  
        url : "/store/provident-living"  
    }  
]  

我一直试图将此渲染为无序列表,其中包含嵌套的UL结构,该结构遵循URL路径结构,如下所示:

<ul>  
    <li><a href="/store">Store</a>  
        <ul>  
        <li><a href="/store/travel">Travel</a></li>  
        <li><a href="/store/gardening">Gardening</a></li>  
        <li><a href="/store/healthy-eating">Healthy Eating</a>  
            <ul>  
            <li><a href="/store/healthy-eating/cook-books">Cook Books</a></li>  
            <li><a href="/store/healthy-eating/single-meal-gifts">Single Meal Gifts</a></li>
            </ul>  
        </li>
        <li><a href="/store/outdoor-recreation">Outdoor Recreation</a>  
            <ul>  
            <li><a href="/store/outdoor-recreation/hiking">Hiking</a>  
                <ul>  
                <li><a href="/store/outdoor-recreation/hiking/snowshoeing">Snowshoeing</a></li>
                </ul>  
            </li>  
            <li><a href="/store/outdoor-recreation/skiing">Skiing</a></li>  
            </ul>  
        </li>
        <li><a href="/store/physical-fitness">Physical Fitness</a></li>  
        <li><a href="/store/provident-living">Provident Living</a></li>  
        </ul>  
    </li>  
</ul>  

我看到的所有示例都以反映父子关系的数据结构(例如xml或JSON)开头,但是我很难将其从URL中拉出并使用它来渲染新结构。

如果有人可以请我指导我使用jQuery如何做到这一点,我真的很感激。我意识到我可能需要使用一些递归函数或jQuery模板,但这些对我来说仍然有点新鲜。
感谢

6 个答案:

答案 0 :(得分:8)

我认为最好的解决方案是首先将您的数据结构转换为具有父/子关系的树。然后渲染此结构将更容易,因为UL本身具有树结构。

您可以使用这几个函数转换menuItem

// Add an item node in the tree, at the right position
function addToTree( node, treeNodes ) {

    // Check if the item node should inserted in a subnode
    for ( var i=0; i<treeNodes.length; i++ ) {
        var treeNode = treeNodes[i];

        // "/store/travel".indexOf( '/store/' )
        if ( node.url.indexOf( treeNode.url + '/' ) == 0 ) {
            addToTree( node, treeNode.children );

            // Item node was added, we can quit
            return;
        }
    }

    // Item node was not added to a subnode, so it's a sibling of these treeNodes
    treeNodes.push({
        name: node.name,
        url: node.url,
        children: []
    });
}

//Create the item tree starting from menuItems
function createTree( nodes ) {
    var tree = [];

    for ( var i=0; i<nodes.length; i++ ) {
        var node = nodes[i];
        addToTree( node, tree );
    }

    return tree;
}

var menuItemsTree = createTree( menuItems );
console.log( menuItemsTree );

生成的menuItemsTree将是一个像这样的对象

[
  {
    "name":"Store",
    "url":"/store",
    "children":[
      {
        "name":"Travel",
        "url":"/store/travel",
        "children":[

        ]
      },
      {
        "name":"Gardening",
        "url":"/store/gardening",
        "children":[

        ]
      },
      {
        "name":"Healthy Eating",
        "url":"/store/healthy-eating",
        "children":[
          {
            "name":"Cook Books",
            "url":"/store/healthy-eating/cook-books",
            "children":[

            ]
          },
          {
            "name":"Single Meal Gifts",
            "url":"/store/healthy-eating/single-meal-gifts",
            "children":[

            ]
          }
        ]
      },
      {
        "name":"Outdoor Recreation",
        "url":"/store/outdoor-recreation",
        "children":[
          {
            "name":"Hiking",
            "url":"/store/outdoor-recreation/hiking",
            "children":[
              {
                "name":"Snowshoeing",
                "url":"/store/outdoor-recreation/hiking/snowshoeing",
                "children":[

                ]
              }
            ]
          },
          {
            "name":"Skiing",
            "url":"/store/outdoor-recreation/skiing",
            "children":[

            ]
          }
        ]
      },
      {
        "name":"Physical Fitness",
        "url":"/store/physical-fitness",
        "children":[

        ]
      },
      {
        "name":"Provident Living",
        "url":"/store/provident-living",
        "children":[

        ]
      }
    ]
  }
]

你提到你已经有了树的html渲染器,对吧?如果您需要进一步的帮助,请告诉我们!

答案 1 :(得分:2)

12行简单的代码:

var rootList = $("<ul>").appendTo("body");
var elements = {};
$.each(menuItems, function() {
    var parent = elements[this.url.substr(0, this.url.lastIndexOf("/"))];
    var list = parent ? parent.next("ul") : rootList;
    if (!list.length) {
        list = $("<ul>").insertAfter(parent);
    }
    var item = $("<li>").appendTo(list);
    $("<a>").attr("href", this.url).text(this.name).appendTo(item);
    elements[this.url] = item;
});

http://jsfiddle.net/gilly3/CJKgp/

答案 2 :(得分:2)

虽然我喜欢gilly3的脚本,但脚本会生成列表,其中<li><ul>的元素嵌套比最初要求的要多。所以而不是


   <li><a href="/store">Store</a>
     <ul>
        <li><a href="/store/travel">Travel</a></li>
        ...
     </ul>
   </li>
它产生

   <li><a href="/store">Store</a>
   </li>
   <ul>
      <li><a href="/store/travel">Travel</a></li>
      ...
   </ul>
这可能导致与此类生成的菜单一起使用的实用程序或框架不兼容,并生成带动画的交互式菜单(例如superfish.js)。 所以我更新了12行脚本

var rootList = $("<ul>").appendTo("body");
var elements = {};
$.each(menuItems, function() {
    var parent = elements[this.url.substr(0, this.url.lastIndexOf("/"))];
    var list = parent ? parent.children("ul") : rootList;
    if (!list.length) {
        list = $("<ul>").appendTo(parent);
    }
    var item = $("<li>").appendTo(list);
    $("<a>").attr("href", this.url).text(this.name).appendTo(item);
    elements[this.url] = item;
});

http://jsfiddle.net/tomaton/NaU4E/

答案 3 :(得分:0)

这不是jQuery,但也许这可能会有所帮助。我在寻求网络完成你想要的东西后开发了这个。

http://www.chapleau.info/article/ArrayofUrlsToASitemap.html

答案 4 :(得分:0)

尝试这样的事情。

function Directory(parentNode) {
    //Structure for directories.  Subdirectories container as a generic object, initially empty
    this.hasSubdirectories = false;
    this.subdirectories = {};

    //Render in steps.  Until subdirectories or a link are added, all it needs is an LI and a blank anchor
    this.nodeLi = document.createElement("li");
    parentNode.appendChild(this.nodeLi);
    this.nodeA = document.createElement("a");
    this.nodeLi.appendChild(this.nodeA);

    //if a subdirectory is added, this.nodeUl will be added at the same time.
}

Directory.prototype.setLabel = function (sLabel) {
    this.nodeA.innerHTML = sLabel;
}

Directory.prototype.setLink = function (sLink) {
    this.nodeA.href = sLink;
}

Directory.prototype.getSubdirectory = function (sPath) {
    //if there were no previous subdirectories, the directory needs a new UL node.
    if (!this.hasSubdirectories) {
        this.nodeUl = document.createElement("ul");
        this.nodeLi.appendChild(this.nodeUl);
        this.hasSubdirectories = true;
    }

    //split the path string into the base directory and the rest of the path.
    var r = /^\/?(?:((?:\w|\s|\d)+)\/)(.*)$/;
    var path = r.exec(sPath);

    //if the desired path is in a subdirectory, find or create it in the subdirectories container.

    var subDirName = path[1] || path[2];
    var subDir;
    if (this.subdirectories[subDirName] === undefined) this.subdirectories[subDirName] = new Directory(this.nodeUl);
    subDir = this.subdirectories[subDirName];

    if (path[1] && path[2]) {
        return subDir.getSubdirectory(path[2]);
    } else {
        return subDir;
    }
}

function main(whichNode, aMenuItems) {
    //whichNode is the node that is to be the parent of the directory listing.
    //aMenuItems is the array of menu items.
    var i;
    var l = aItems.length;
    var topDir = new Directory(whichNode);

    //for each menu item, add a directory and set its properties.
    var dirToAdd;
    for (i = 0; i < l; i++) {
        dirToAdd = topDir.getSubdirectory(aMenuItems[i].url);
        dirToAdd.setLabel(aMenuItems[i].name);
        dirToAdd.setLink(aMenuItems[i].url);
    }

    //and that's it.
}

那是怎么回事?

答案 5 :(得分:0)

或者可能是完整的jQuery插件http://jsfiddle.net/9FGRC/

(编辑)

对先前版本http://jsfiddle.net/9FGRC/1/的更新

此版本支持以下案例

var menuItems = [  
    {  
        name : "Store",  
        url : "/store"  
    },  
    {  
        name : "Cook Books",  
        url : "/store/healthy-eating/cook-books"  
    },  
    {  
        name : "Single Meal Gifts",  
        url : "/store/healthy-eating/single-meal-gifts"  
    }  
]  

因为跳过了

    {  
        name : "Healthy Eating",  
        url : "/store/healthy-eating"  
    },

它将产生以下html

<ul>
    <li><a href="/store">Store</a>
        <ul>
            <li><a href="/store/healthy-eating/cook-books">Cook Books</a></li>
            <li><a href="/store/healthy-eating/single-meal-gifts">Single Meal Gifts</a></li>
        </ul>
    </li>
</ul>

我想情况并非如此,但对某人有帮助