JS树 - select_node不工作

Jam*_*itt 6 ajax jquery jstree

我对JSTree和Ajax有一个奇怪的问题.

我通过Ajax/PHP请求生成我的树,它使用...生成HTML(带有UL,LI,A标签)

$.ajax({
    url: 'ajaxTreeView.php?method=edit&partid='+partId,
    cache: false,
    success: function(tree)
    {
        $('#treeViewer').html(tree);
    }});
Run Code Online (Sandbox Code Playgroud)

并使用...激活代码上的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);
Run Code Online (Sandbox Code Playgroud)

我似乎无法轻松选择节点.我尝试过initial_select,但这似乎不起作用,也不理想,因为我经常想以编程方式选择节点.

我试过用...

$('#tree').jstree("select_node", '#ref565', true);
Run Code Online (Sandbox Code Playgroud)

如果我通过超链接调用该函数但是如果我在初始化JStree之后调用它,则无效.

我看到添加一个警报(所有这些都发生在Ajax Success例程中)......

$('#treeViewer').html(tree);
$("#tree").jstree(options);
alert('test');
$('#tree').jstree("select_node", '#ref565', true);
Run Code Online (Sandbox Code Playgroud)

...在警报开始之前树没有渲染.

我添加了一个setTimeOut ...

$('#treeViewer').html(tree);
$("#tree").jstree(options);
setTimeout(function() {selectNode(565);},1250);
$('#tree').jstree("select_node", '#ref565', true);
Run Code Online (Sandbox Code Playgroud)

......这很有效.

我显然很愚蠢.我使用了错误的语法吗?为什么我必须设置延迟才能选择节点?

请帮忙.

Boj*_* Li 9

如果您想在树加载后最初选择某些节点,则应该使用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", '#ref565', true); 
        }) 
});
Run Code Online (Sandbox Code Playgroud)