首页 > 解决方案 > jsTree - is_parent() 返回错误值

问题描述

我正在从远程服务器请求数据,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);

标签: javascriptjsonjstree

解决方案


得到父母

利用

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>


推荐阅读