Javascript 以编程方式将子节点添加到 jstree
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3479715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically adding child nodes to a jstree
提问by user419766
I'm trying to write some code that adds nodes to a jstree dynamically. I've followed the doc at http://www.jstree.com/documentation/crrmbut can't get a simple example to work -- the node child2 is being added, but it is being added to the node 'root.id' rather than 'child1.id' as specified... Any tips would be much appreciated. Code follows
我正在尝试编写一些将节点动态添加到 jstree 的代码。我遵循了http://www.jstree.com/documentation/crrm 上的文档,但无法获得一个简单的示例来工作——正在添加节点 child2,但它正在添加到节点“root”。 id' 而不是指定的 'child1.id' ......任何提示将不胜感激。代码如下
<html>
<head>
<script type="text/javascript" src="http://static.jstree.com/v.1.0rc2/jquery.js"></script>
<script type="text/javascript" src="http://static.jstree.com/v.1.0rc2/jquery.jstree.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(function () {
$("#tree").jstree({
"json_data" : {
"data" : [
{
"data" : "parent",
"attr" : { "id" : "root.id" },
"children" : [ { "data" : "child1",
"attr" : { "id" : "child1.id" },
"children" : [ ] }
]
},
]
},
"plugins" : [ "themes", "json_data", "crrm" ]
});
});
$("#add").click(function() {
$("#tree").jstree("create", $("#child1.id"), "inside", { "data" : "child2" },
function() { alert("added"); }, true);
});
});
</script>
</head>
<body>
<div id="tree" name="tree"></div>
<input type="button" id="add" value="add" />
</body>
</html>
回答by WSkid
When using periods in ID's you need to escape them like so:
在 ID 中使用句点时,您需要像这样转义它们:
$("#tree").jstree("create", $("#child1\.id"), "inside", { "data" : "child2" },
function() { alert("added"); }, true);
This is because of how it uses jQuery selectors. It is mentioned in the jsTree FAQ located here: http://www.jstree.com/faq/
这是因为它如何使用 jQuery 选择器。它在位于此处的 jsTree 常见问题解答中提到:http: //www.jstree.com/faq/
回答by Tales
first initialize jstree(in my case i use ajax), put check_callback into core obj and call the plugin after core obj like this:
首先初始化jstree(在我的情况下我使用ajax),将check_callback放入核心obj并在核心obj之后调用插件,如下所示:
jQuery('#jstree_demo_div').jstree({
'core' : {
'data' : {
'url' : 'data/mapas.php',
},
"check_callback" : function(e,data){
console.log(data)
}
},
"plugins" : [ "contextmenu" ] })
second use this line and put $('#j1_1') as parent , the data in json, 'last' as position or 'first', the function callback (in my case is the function tales()), internal argument set in true
第二次使用这一行并将 $('#j1_1') 作为父级,json 中的数据,'last' 作为位置或'first',函数回调(在我的例子中是函数 tales()),内部参数设置在真的
jQuery("#jstree_demo_div").jstree(true).create_node( $('#j1_1'), {text: "New node", id: true} , "last",tales(), true );

