如何将数据关联到jstree中的节点?

Abh*_*hii 16 jquery jquery-plugins jstree

$("#ifTree").jstree({
            "plugins" : ["themes","html_data","ui","crrm"], 
            "themes" : {
                    "theme" : "apple",
                    "dots" : true,
                    "icons" : false
            }           
    });

    $("#createIf_c").click(function () { 
        $("#ifTree").jstree("create",null,"inside",  { "data" :{ title:"if",value:"expression"} },
                function() {}, true);
    });
$("#display").click(function(){
            var a = $.jstree._focused().get_selected();
            alert(a.attr("value"));
    });
Run Code Online (Sandbox Code Playgroud)

在上面这段代码中,我创建了一个jstree,点击了一个id为#createIf_c的按钮,我添加了一个标题为"if"的节点,但由于我想要更多的数据与这个节点相关联,我为它添加了更多属性在创建节点时.接下来,当我尝试访问此关联数据时,此处为"值",然后我收到警报"未定义".那么将数据与节点关联有不同的方法吗?或者以不同的方式访问节点的关联数据是jstree?..请帮助....

小智 17

您可以将您的额外数据放在JSON node.data中,但这没有记录
在此输入图像描述

  • 真棒.这正是我所寻找的 (3认同)

Ace*_*Ace 13

Plz参考作者的答案.

您可以通过编辑信息$('#tree').jstree(true).get_node("some_node_id"),并将额外数据发布为json $('#tree').jstree(true).get_json("some_node_id").

You can add anything you want to the data object. Like:
{ "id" : "some_node_id" "text" : "some node", ... "data" : { "foo" : "bar", "example_array" : ["1",2,true], "obj" : {"asdf":"asdf1"}  } ...

And later on you can retrieve it like so:
$('#tree').jstree(true).get_node("some_node_id").data.obj.asdf; // this would equal "asdf1"
$('#tree').jstree(true).get_node("some_node_id").data.example_array; // this would be an array: ["1",2,true]

Setting other values is just as simple - you are working with a normal object:
$('#tree').jstree(true).get_node("some_node_id").data.obj.asdf = "some other value";
$('#tree').jstree(true).get_node("some_node_id").data.example_array = "I do not want this an array anymore";
$('#tree').jstree(true).get_node("some_node_id").data.obj.new_property = 1024;
Run Code Online (Sandbox Code Playgroud)


Abh*_*hii 5

最简单的方法就是向 html 元素添加属性,即

    var node = $.jstree._focused().get_selected(); //get the selected node or which ever you want the data to be associated with
    node.attr("expression","xyz"); //add an attribute (name,value) here, name-expression and value-xyz
Run Code Online (Sandbox Code Playgroud)