js怎样将获取json转换为树形结构

JavaScript018

js怎样将获取json转换为树形结构,第1张

比如这样一段json

{

"name":"1级菜单1",

"link":"###",

"isleaf": false,

"level": 0,

"children": [

{

"name":"2级菜单1",

"link":"###",

"isleaf": false,

"level": 1,

"children": [

{

"name":"3级菜单1",

"link":"###",

"isleaf": true,

"level": 2,

"children": null

},

{

"name":"3级菜单2",

"link":"###",

"isleaf": true,

"level": 2,

"children": null

}

]

},

{

"name":"2级菜单2",

"link":"###",

"isleaf": false,

"level": 1,

"children": [

{

"name":"3级菜单3",

"link":"###",

"isleaf": true,

"level": 2,

"children": null

}

]

}

]

}

我怎样把他转换成

<div>

<a href="###">一级菜单</a>

<ul>

<li>

<a>2级菜单1</a>

<ul>

<li><a href="###">3级菜单1</a></li>

<li><a href="###">3级菜单2</a></li>

</ul>

</li>

<li>

<a href="###">2级菜单2</a>

.......

</li>

</ul>

</div>

思路就是:找出父节点的所有子节点的checked的属性设置成与父节点一致即可

我是利用jquery实现,看看是否符合你的要求

<script src="../lib/jquery.js" type="text/javascript"></script>

<script src="../jquery.treeview.js" type="text/javascript"></script>

<script type="text/javascript">

$(function(){

$("#tree").treeview()

$("input[name='ids']").click(function(){

var checkedValue = this.checked

$(this).parent("li").find("input[name='ids']").attr("checked",checkedValue)

})

})

</script>

<ul id='tree'>

<li>

<input type='checkbox' name='ids' id="test"/>

<span class='folder'>test1</span>

<ul>

<li>

<input type='checkbox' name='ids' />

<span class='folder'>test11</span>

</li>

</ul>

<ul>

<li>

<input type='checkbox' name='ids' />

<span class='folder'>test12</span>

<ul>

<li>

<input type='checkbox' name='ids' />

<span class='folder'>test121</span>

</li>

</ul>

</li>

</ul>

</li>

</ul>