javascript jsTree:通过 Id 获取节点并创建一个子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23791015/
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
jsTree: Getting a node by Id and creating a child
提问by ps0604
I've found in several places on the web the jsTree create/get_node functions but cannot make this work. When a user clicks on a button, I need to get the parent node using its Id and create a child (see jsfiddle). What's wrong with this code?
我在网络上的几个地方找到了 jsTree create/get_node 函数,但无法使其工作。当用户单击按钮时,我需要使用其 Id 获取父节点并创建一个子节点(请参阅jsfiddle)。这段代码有什么问题?
This is the HTML:
这是 HTML:
<form>
<input value="Create Child" type="button" onclick="createChild();" />
</form>
<div id="treediv" />
And this is the javascript:
这是javascript:
var sqltree = [
{ "data" : "Node1", "metadata": { "id" : "id1" } , "attr":{"rel":"rel1"} },
{ "data" : "Node2", "metadata": { "id" : "id2" }, "attr":{"rel":"rel2"} },
{ "data" : "Node3", "metadata": { "id" : "id3" }, "attr":{"rel":"rel3"} }
];
$("#treediv").jstree({
"json_data" : { "data" : sqltree },
"plugins" : [ "json_data", "ui", "crrm", "types" ]
});
function createChild(){
alert ('createChild invoked');
var newNode = { data: "Child1" };
var parentNode = $('#treediv').get_node("[id='id2']");
$("#treediv").jstree("create",parentNode,"first",newNode,false,true);
}
回答by Lucidity
If you reference the jsTree instance:
如果您引用 jsTree 实例:
treeInst = $('#treediv').jstree() # create new instance
treeInst = $('#treediv').jstree(true) # get existing instance
Then you can get a node by it's id:
然后你可以通过它的 id 获取一个节点:
node = treeInst.get_node( node_id )
回答by juvian
Change :
改变 :
var parentNode = $('#treediv').get_node("[id='id2']");
To:
到:
var parentNode = $('#treediv').find("[id='id2']");