使用zTree和json构建简单树节点

我们经常碰到须要构建树结构展示的情况,我推荐使用zTreeJSON

比如:

<?

php
/**
* * 使用zTree和json构建树节点
* */
$arr = array(
0=>array(
'id' => 1,
'pid' => 0,
'name' => 'china',
'son' => array(
array(
'id' => 3,
'pid' => 1,
'name' => 'Beijing',
),
array(
'id' => 5,
'pid' => 1,
'name' => 'Nanjing',
'son' => array(
array(
'id' => 7,
'pid' => 1,
'name' => 'Jiangning',
)
),
),
),
),
1=>array(
'id' => 2,
'pid' => 0,
'name' => 'USA',
'son' => array(
array(
'id' => 4,
'pid' => 2,
'name' => 'Washington',
),
array(
'id' => 6,
'pid' => 2,
'name' => 'New York',
),
),
),
);
function json_string($arr){
echo(str_replace("son","children",json_encode($arr)));//zTree中下级用children表示,json_encode仅仅支持utf-8编码
}
json_string($arr);
? >
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML4.01//EN" "http://www.w3.org/TR/html4/strict.dtd”>
<HTML>
<HEAD>
<TITLE> ZTREE DEMO </TITLE>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<link rel="stylesheet" href="../css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../js/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript">
function zTreeInit() {
var zTreeObj;
var setting = {};
var zNodes = eval(<?php json_string($arr) ? > );
zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
}
$(document).ready(function () {
zTreeInit();
});
</script>
</HEAD>
<BODY>
<div>
<ul id="treeDemo" class="ztree"></ul>
</div>
</BODY>
</HTML>

输出效果例如以下:

使用zTree和json构建简单树节点

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYnVidTg2MzM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

上一篇:Python 零基础 快速入门 趣味教程 (咪博士 海龟绘图 turtle) 4. 函数


下一篇:Android Studio | 详细安装教程