我在使用json文件(或任何东西)填充这个jquery treeselect小部件时遇到问题我是jquery / javascript的新手,所以我可能错过了一些基础知识。
我有来自https://github.com/travist/jquery.treeselect.js的插件,但没有找到如何加载它的示例。
<html>
<head>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script>
<script type='text/javascript' src='js/jquery.moreorless.js'></script>
<script type='text/javascript' src='js/jquery.treeselect.js'></script>
<script type='text/javascript' src='js/jquery.chosentree.js'></script>
<link rel='stylesheet' type='text/css' href='css/moreorless.css'/>
<link rel='stylesheet' type='text/css' href='css/treeselect.css'/>
<link rel='stylesheet' type='text/css' href='css/chosen.css'/>
<script type='text/javascript'>
jQuery(function () {
var data1 = ["EVENT1", "EVENT2"];
var data2 = [{
"id": 1,
"name": "A green door"
},
{
"id": 2,
"name": "A blue door"
}
]
$('div.chosentree').chosentree({
width: 200,
deepLoad: true,
default_value: data2, // does not work
load: function (node, callback) {
// What do I put here?
/**
* This would typically call jQuery.ajax to load a new node
* on your server where you would return the tree structure
* for the provided node.
*/
}
});
});
</script>
</head>
<body>
<div class="chosentree"></div>
</body>
</html>
答案 0 :(得分:2)
想发布这段代码,因为我花了最后2个小时认为它不会采用原始JSON。确实如此,但不要忘记通过JSON.parse(jsonString)运行你的字符串文字;
示例:
jQuery(function() {
JSONObject = JSON.parse('{"id":"01","title":"Node 01","has_children":true,"level":1,"children":[{"id":"011","title":"Node 011","has_children":true,"level":2,"children":[{"id":"0111","title":"Node 0111","has_children":false,"level":3,"children":[]}]}]}');
$('div.chosentree').chosentree({
width: 500,
deepLoad: true,
load: function(node, callback) {
callback(JSONObject);
}
});
});
答案 1 :(得分:1)
了解其工作原理的最佳方法是查看在@ https://github.com/travist/jquery.treeselect.js/blob/master/treeselect.html找到的repo中提供的示例文件。在这里,您将看到以下代码。
$('div.chosentree').chosentree({
width: 500,
deepLoad: true,
showtree: true,
load: function(node, callback) {
setTimeout(function() {
callback(loadChildren(node, 0));
}, 1000);
}
});
此处load
方法中的代码实际上是对数据的外观执行虚假请求。它通过调用名为loadChildren
的方法来完成此操作,该方法在找到的文件@ https://github.com/travist/jquery.treeselect.js/blob/master/index.html中定义。以下是......
var maxDepth = 3;
var loadChildren = function(node, level) {
var hasChildren = node.level < maxDepth;
for (var i=0; i<8; i++) {
var id = node.id + (i+1).toString();
node.children.push({
id:id,
title:'Node ' + id,
has_children:hasChildren,
level: node.level + 1,
children:[]
});
if (hasChildren && level < 2) {
loadChildren(node.children[i], (level+1));
}
}
return node;
};
重要的是要意识到这是“伪造”对服务器的请求。这基本上会向服务器发送一个请求,该服务器将返回类似于以下内容的内容。
{
"id": "1",
"title": "Node 1",
"has_children": "1",
"children": [
{
"id": "11",
"title": "Node 11",
"has_children": "1",
"children": [
]
},
...
...
]
}
然后通过传入单个节点对象来调用load
方法,如果您愿意,可以使用该对象加载该节点下的所有子节点。
我希望这会有所帮助。