jsTree:如何在遍历树时获取节点的元数据?

时间:2014-05-30 22:12:45

标签: javascript jstree

我已经看到许多在选择节点时获取节点元数据的答案(select_node绑定),但我想要实现的是首先从节点获取子节点然后迭代它们到获取元数据。这jsfiddle试图这样做。这段代码有什么问题?

这是HTML:

<form>
    <input value="List Nodes Metadata" type="button" onclick="listNodesMetadata();" />
</form>

<div id="treediv" />

这是javascript:

$(document).ready(function () {

var tree = [ { "data" : "Node1", metadata: { x: "x1"  }, "attr":{"rel":"rel1",  "id" : "id1"} },
             { "data" : "Node2", metadata: { x: "x2"  },  "attr":{"rel":"rel2",  "id" : "id2"} },
             { "data" : "Node3", metadata: { x: "x3"  }, "attr":{"rel":"rel3",  "id" : "id3"} }
         ];

  $("#treediv").jstree({
            "json_data" : { "data" : tree },
            "plugins" : [ "json_data", "ui", "crrm", "types" ]
    });

});  


function listNodesMetadata(){

    var nodes = jQuery.jstree._reference("#treediv")._get_children(-1);
    var len = nodes.length;

    for (var i=0;i<len;i++) {
        alert ( i + " " + nodes[i].data('x') );
    }

}

1 个答案:

答案 0 :(得分:0)

答案在jsfiddle。为每个子节点获取id,使用find函数获取jsTree节点,然后从节点使用数据函数访问元数据。

var nodes = jQuery.jstree._reference("#treediv")._get_children(-1);
var len = nodes.length;

for (var i=0;i<len;i++) {
    var node = $('#treediv').find("[id='" + nodes[i].id + "']");
    alert ( nodes[i].id + " " + node.data('x') );
}