在JavaScript中访问FancyTree节点数据

She*_* R. 1 html javascript fancytree

我第一次使用FancyTree,我想定义一些自定义节点数据,特别是用于创建树的HTML数据中名为"content"的属性:

    <li id="xxxx" data-content="true"  class="folder">
Run Code Online (Sandbox Code Playgroud)

我有一个用JavaScript编写的init事件处理程序,我想在那里访问我的自定义数据属性:

init: function(event, data, flag)
   {
    var tree = $("#tree").fancytree("getTree");
    node = tree.getNodeByKey(key);
    var data = node.data;
Run Code Online (Sandbox Code Playgroud)

在一个在线教程中,我看到我的自定义属性可以作为node.data.content访问,但是我无法在警告框中显示我的自定义属性以证明它实际已定义.如何在JavaScript函数中访问自定义数据属性?

谢尔顿

小智 6

好的,所以我终于搞定了.你接近得到你的结果.

键变量是一个字符串,表示树中每个LI元素的"id"属性.您将获得具有该密钥的节点.获取节点后,您可以检索与该节点关联的自定义数据属性.由于我们的'data'变量是一个包含键/值的对象,因此您需要在数据对象上调用它的'key'名称来检索值,就像'data.content'一样.

JS

$(function () {
    // using default options
    //Caching DOM element
    var $myTree = $("#tree").fancytree();
    // Get the DynaTree object instance
    var tree = $myTree.fancytree("getTree");
    //Set my key
    var key = "id1";
    //Get the node
    var node = tree.getNodeByKey(key);
    //Get the custom data attribute associated to that node
    var data = node.data;
    //data is an object so, data.content will give you the value of the attribute
    alert(data.content);
});
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

希望这可以帮助!