jsTree-is_parent()返回错误的值

时间:2018-11-23 06:33:23

标签: javascript json jstree

我正在从具有json返回格式的远程服务器请求数据:

[
{"id":"1", "parent": "#", "text" : "Parent1"},
{"id":"2", "parent": 1, "text" : "Child1"}
{"id":"3", "parent": 2, "text" : "Child12"}
{"id":"4", "parent": 1, "text" : "Child2"}
{"id":"5", "parent": 1, "text" : "Child3"}
{"id":"6", "parent": 4, "text" : "Child21"}
]

我想检查所选节点是否为父节点。我使用以下代码:

$('#treeview').on("select_node.jstree", function (e, data) {
        var isParent = data.instance.is_parent(); 
        alert(isParent)
    });

即使我单击PARENT,它始终返回false。

我在这里想念什么?

更新 这就是我解决问题的方式。但是我仍然想知道为什么is_parent()is_leaf()方法不起作用

var isParent = (data.node.children.length > 0);

1 个答案:

答案 0 :(得分:1)

要成为父母

使用

var isParent = (data.node.children.length > 0);
alert(isParent );

$('#treeview').jstree({
  'core': {
    'data': [{
        "id": "1",
        "parent": "#",
        "text": "Parent1"
      }, {
        "id": "2",
        "parent": 1,
        "text": "Child1"
      },
      {
        "id": "21",
        "parent": 2,
        "text": "Child1"
      },
      {
        "id": "3",
        "parent": 2,
        "text": "Child12"
      }, {
        "id": "4",
        "parent": 1,
        "text": "Child2"
      }, {
        "id": "5",
        "parent": 1,
        "text": "Child3"
      },
      {
        "id": "6",
        "parent": 4,
        "text": "Child21"
      },
      {
        "id": "7",
        "parent": '#',
        "text": "Parent 2"
      },
      {
        "id": "8",
        "parent": 7,
        "text": "Child"
      }
    ]
  }
});

$('#treeview').on("select_node.jstree", function(e, data) {
  // var isParent = data.instance.is_parent(data);
  // If you need to check if a node is a root node you can use:
  var isParent = (data.node.children.length > 0);
  console.log(data.node);
  alert(isParent)
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

<div id="treeview"></div>