jsTree是一个漂亮的轻量级jquery树形构建包,但在与它一起工作几天后,我对在线文档缺乏明确和有用的描述感到不满。
为了帮助未来的开发人员解决问题而不必花费数小时或数天来摸索,我在下面列出了一些方法。我相信编写这个代码的方法可能更加优雅或最佳实践,但我找不到任何不涉及将ajax方法构建到jstree函数本身中的示例(在我的情况下绝对不是一种选择)。在下面的示例中,我可以自由地在makeTree()中调用Ajax方法以获取我的数据,按照自己的方式构建JSON并手动将其插入到树中。
无论如何,下面是我创建的一些示例代码,用于在页面加载时构建树,在emptyTree ()中清空所有节点的树,并通过JSON重新构建树形结构makeTree()。这显然是一个不完整的参考,但如果您只需要快速且简单的方法来使用此包完成我正在做的事情,那么您可能会喜欢这个。
$(document).ready(function(){
$("#myJSTree").jstree({
'core' : {
'check_callback' : true
}
});
});
function emptyTree()
{
var myTree = $("#myJSTree").jstree(true);
$("#myJSTree .jstree-leaf, .jstree-anchor").each(function(){
myTree.delete_node($(this).attr('id'));
});
}
function makeTree()
{
var myTree = $("#myJSTree").jstree(true);
// This JSON is just an example, you can create it how you need it, I'll include the sample Valid JSON at the bottom for reference.
var nodesJSON = { "text": "Passed Testing", "icon": "images/success.png", "state": { "opened": true }, "children": [{ "text": "Passed Testing", "icon": "images/success.png", "state": { "opened": true }},{ "text": "Passed Testing", "icon": "images/success.png", "state": { "opened": true }}]};
myTree.create_node("#", nodesJSON, "last", function() {}, true);
}
// Adding the HTML that gets built into the tree at page load in my example
<div id="myJSTree">
<ul>
<li>Node 1</li>
<li class="jstree-open">
<ul>
<li>SubNode 1</li>
<li>SubNode 2</li>
</ul>
</li>
<li>Node 2</li>
</ul>
</div>
// Valid JSON format that took me a while to find on the jstree website
// I didn't write these. it's copied and pasted.
// sample JSON 1
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
// Sample JSON 2
{
id : "string" // required
parent : "string" // required
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
如果您有更好的方法来完成这个任务,请随意分享您的见解,但是这个软件包的文档对我来说并不是非常直观。我已经仔细阅读了他们的网页,但是感觉很痛苦。