javascript - 怎么将层级关系明确但层级不确定的数据拼成层级对应的html字符串?

查看:120
本文介绍了javascript - 怎么将层级关系明确但层级不确定的数据拼成层级对应的html字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

假如数据如下

var a=[
{
    "cdept": "001",
    "name": "公司",
    "children": [
        {
            "cdept": "001001",
            "name": "部门",
            "children": [
                {
                    "cdept": "001001001",
                    "name": "xx组",
                    "children": [
                        
                    ]
                },
                {
                    "cdept": "001001002",
                    "name": "xx2组",
                    "children": [
                        
                    ]
                }
            ]
        },
        {
            "cdept": "001002",
            "name": "部门2",
            "children": [
                {
                    "cdept": "001002001",
                    "name": "YY组",
                    "children": [
                        
                    ]
                }
            ]
        }
    ]
} ]

想渲染成对应层级关系的html如

<ul>
   <li>
   <a href="#">公司<a>
   <ul>
    <li>
        <a href="#">部门<a>
        <ul>
            <li>
            <a href="#">xx组<a>
            </li>
        </ul>
        <ul>
            <li>
            <a href="#">xx2组<a>
            </li>
        </ul>
    </li>
</ul>
  <ul>
    <li>
        <a href="#">部门2<a>
        <ul>
           <li>
           <a href="#">YY组<a>
           </li>
        </ul>
    </li>
</ul>
<li> </ul>

每层的html结构都一样。但是层级不确定。可能组下面还有层级。可能没有。我该怎么写js呢?

解决方案

层级没有过深的话,可以递归:

function recGenerator(json){
    if(!json || !(''+json)){//没有children或者children为空
        innHtml="<ul><li><a href='#'>"+json.name+"</a></li></ul>";
    }else{
        var childrenHtml="";
        var i=0;
        while(json.children[i]){
            childrenHtml+=recGenerator(json.children[i++]);
        }
        innHtml="<ul><li><a href='#'>"+json.name+"</a>"+childrenHtml+"</li></ul>";
    }
    return innHtml;
}

console.log(recGenerator(a[0]));

<ul><li><a href='#'>公司</a><ul><li><a href='#'>部门</a><ul><li><a href='#'>xx组</a></li></ul><ul><li><a href='#'>xx2组</a></li></ul></li></ul><ul><li><a href='#'>部门2</a><ul><li><a href='#'>YY组</a></li></ul></li></ul></li></ul>

这篇关于javascript - 怎么将层级关系明确但层级不确定的数据拼成层级对应的html字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆