我对JSTree和Ajax有一个奇怪的问题.
我通过Ajax / PHP请求生成我的树,它使用…生成HTML(带有UL,LI,A标签)
$.ajax({ url: 'ajaxTreeView.PHP?method=edit&partid='+partId,cache: false,success: function(tree) { $('#treeViewer').html(tree); }});
并使用…激活代码上的JStree
options = { "core": { animation: 120 },"themes": { theme: 'corral',dots: true },"types": { "types": { "parent": { "icon": { "image": "images/custom/Legend/node_select.png" } },"child": { "icon": { "image": "images/custom/Legend/node_select_child.png" } },"current": { "icon": { "image": "images/custom/Legend/node.png" } } } },"plugins": [ "html_data","types","themes","ui","contextmenu","cookies" ],"ui": { "select_limit" : 1 },"cookies": { "save_selected" : false } }; $("#tree").jstree(options);
我似乎无法轻松选择节点.我尝试过initial_select,但这似乎不起作用,也不理想,因为我经常想以编程方式选择节点.
我试过用…
$('#tree').jstree("select_node",'#ref565',true);
如果我通过超链接调用该函数但是如果我在初始化JStree之后调用它,则无效.
我看到添加一个警报(所有这些都发生在Ajax Success例程中)……
$('#treeViewer').html(tree); $("#tree").jstree(options); alert('test'); $('#tree').jstree("select_node",true);
…在警报开始之前树没有渲染.
我添加了一个setTimeOut …
$('#treeViewer').html(tree); $("#tree").jstree(options); setTimeout(function() {selectNode(565);},1250); $('#tree').jstree("select_node",true);
……这很有效.
我显然很愚蠢.我使用了错误的语法吗?为什么我必须设置延迟才能选择节点?
请帮忙.
解决方法
如果要在树加载后首先选择某些节点,则应使用
ui插件的
initially_select
选项.你说你试过了,但我没有看到你在你发布的示例代码中使用它.您确定要提供正确的ID吗?
要以编程方式选择节点,您需要等待要选择的节点首先出现在DOM中.而不是使用超时回调,我猜测绑定到loaded.jstree事件是更正确的,应该在树加载完成后调用,并且所有树元素都在DOM中,然后进行编程选择在那里.
$(function () { $("#tree") .jstree({ // List of active plugins "plugins" : [ "ui" ],// UI & core - the nodes to initially select and open will be overwritten by the cookie plugin // the UI plugin - it handles selecting/deselecting/hovering nodes "ui" : { // this makes the node with ID node_4 selected onload "initially_select" : [ "#ref565" ] },// the core plugin - not many options here "core" : { // just open those two nodes up // as this is an AJAX enabled tree,both will be downloaded from the server "initially_open" : [ "#ref565" ] } }) .bind("loaded.jstree",function (e,data) { $('#tree').jstree("select_node",true); }) });