概述:一般数据都是不是死的我们需要动态的创建节点,具体引用jstree文件入门参考:http://blog.youkuaiyun.com/m0_37355951/article/details/75257556
1、html标签:
<div id="jstree"></div>
2、js文件
$(function () {
$('#jstree').jstree({
'plugins': ["checkbox", "state"],
'core': {
'data': [{
"id": "root",
"text": "根节点",
"state": { //默认状态展开
"opened": true
},
"children": [{ //创建一个子节点
"text": "子节点1",
"id": "child1"
}]
}],
'check_callback': true
}
});
});
//当jsree加载完成会执行如下函数,创建两个节点
$('#jstree').on('ready.jstree', function (e, data) {
createNode("#jstree", "root1", "根节点2", "first"); //最前面插入
createNode("#root", "child2", "子节点2", "last"); //在最后插入
});
// API createNode(parent, id, text, position).
// parent:在该节点下创建,id: 新节点id, text:新节点文本, position:插入位置
// 封装一个函数动态创建节点
function createNode(parent_node, new_node_id, new_node_text, position) {
$('#jstree').jstree('create_node', $(parent_node), { "text":new_node_text, "id":new_node_id }, position, false, false);
}
总结:关键是create_node 方法使用,上面方法可以改为
$('#_jstree').jstree().create_node( $(parent_node), { "text":new_node_text, "id":new_node_id }, position, false, false);
3、整个html文件
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>jstree 插件</title>
<link rel="stylesheet" href="../jstree/themes/default/style.min.css"></link>
<link rel="stylesheet"
href="../bootstrap-3.3.7-dist/css/bootstrap.min.css"></link>
</head>
<body>
<div id="jstree"></div>
<!-- 引入jquery.js -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="../lib/jstree.min.js"></script>
<script type="text/javascript">
$(function () {
$('#jstree').jstree({
'plugins': ["checkbox", "state"],
'core': {
'data': [{
"id": "root",
"text": "根节点",
"state": { //默认状态展开
"opened": true
},
"children": [{ //创建一个子节点
"text": "子节点1",
"id": "child1"
}]
}],
'check_callback': true
}
});
});
//当jsree加载完成会执行如下函数,创建两个节点
$('#jstree').on('ready.jstree', function (e, data) {
createNode("#jstree", "root1", "根节点2", "first"); //最前面插入
createNode("#root", "child2", "子节点2", "last"); //在最后插入
});
// API createNode(parent, id, text, position).
// parent:在该节点下创建,id: 新节点id, text:新节点文本, position:插入位置
// 封装一个函数动态创建节点
function createNode(parent_node, new_node_id, new_node_text, position) {
$('#jstree').jstree('create_node', $(parent_node), { "text":new_node_text, "id":new_node_id }, position, false, false);
}
</script>
</body>
</html>
4、效果:
参考:https://jsfiddle.net/samueltoepke/wh72zf8b/