【问题标题】:jsTree - is_parent() returning wrong valuejsTree - is_parent() 返回错误值
【发布时间】:2018-11-23 06:33:23
【问题描述】:

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

【问题讨论】:

  • @TamilSelvanC 我之前检查过链接,但使用var isParent = data.instance.is_parent(); alert(isParent) 并不能解决问题
  • 嗨,我更新了我的答案。请检查
  • 我明白了。谢谢

标签: javascript json jstree


【解决方案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>

【讨论】:

  • 感谢您的回复@Tamil,但这并不能解决问题。它只适用于根节点。对于树中的任何节点,我想知道它是否是父节点,然后获取它的所有子节点
  • 试试var isParent = (data.node.children.length &gt; 0); alert(isParent );
猜你喜欢
  • 1970-01-01
  • 2019-02-03
  • 2015-06-19
  • 2014-01-16
  • 2019-10-13
  • 2020-10-05
  • 2015-11-19
  • 2020-05-27
  • 2017-04-16
相关资源
最近更新 更多