如何以编程方式选择特定节点?

Geo*_*uer 36 jstree

我有一个jstree.我想选择绑定到id为158的位置的对象的节点.这可行,但似乎很愚蠢.这样做的惯用方法是什么?

var $tree = $('.jstree', myContext),
    node = $tree.find('li').filter(function() { 
        return ( $(this).data().location || {}).id === 158;
    });
$tree.jstree('select_node', n)
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 38

只是想在这里说话,因为没有一个答案对我有用.最后DID的工作非常简单:

$('#someTree').jstree('select_node', 'someNodeId');

请注意,我没有初始化someNodeId为jQuery对象.它只是一个简单的字符串.

我在加载树之后立即执行此操作而未将其置于"准备好"绑定事件中,因为它似乎没有必要.

希望它可以节省一些令人沮丧的时间...

在加载后挂钩到树中:

.on('loaded.jstree', function() {
    // Do something here...
  });
Run Code Online (Sandbox Code Playgroud)


Rad*_*dek 20

基于jsTree组,您可以尝试

jQuery("#getStartedTree").jstree("select_node", "#test2"); 
Run Code Online (Sandbox Code Playgroud)

如果数据看起来像

The JSON in the TextFile.txt - borrowed from your simple example
 [
     {
     "data" : "A node",
     "children" : [ "Child 1", "Child 2" ]
     },
     {
     "attr" : { "id" : "test1" },
         "data" : {
             "title" : "Long format demo",
             "attr" : { "id" : "test2", "href" : "#" }
         }
     }
 ] 
Run Code Online (Sandbox Code Playgroud)

和jsTree设置

My tree container is <div id="getStartedTree">

My jsTree code
 $("#getStartedTree").jstree({
            "themes": {
                "theme": "default",
                "url": "../App_Css/Themes/Default/style.css",
                "dots": true,
                "icons": true
            },
            "json_data": {
                "ajax": {
                    "url": "../SiteMaps/TextFile.txt",
                    "dataType": "json",
                    "data": function(n) {
                        return { id: n.attr ? n.attr("id") : 0 };
                    }
                }
            },
            "plugins": ["themes", "json_data", "ui"]
        }); 
Run Code Online (Sandbox Code Playgroud)

这就是你追求的吗?

  • 什么时候为您的节点分配ID?如何? (2认同)

小智 6

我用以下方法做到了:

$('.jstree').jstree(true).select_node('element id');
Run Code Online (Sandbox Code Playgroud)

这段代码:

jQuery.each(produto.categorias, function(i, categoria) {
    $('#lista-categorias').jstree(true).select_node(categoria.dadoCategoria.id);
});
Run Code Online (Sandbox Code Playgroud)


Suk*_*uta 5

我能够模拟点击 jstree 节点作为选择节点的替代方法。使用的代码如下:

$(treeIdHandle + " li[id=" + nodeId + "] a").click();
Run Code Online (Sandbox Code Playgroud)

  • 这将要求每个节点都有一个 id 属性,这是默认情况下不可用的属性之一(如果是的话,性能会很糟糕)。但是,在您存在 id 的情况下,应该可以简化为 `$('a', '#'+nodeId).click()` (2认同)