仅通过jstree中的简单按钮切换整个树

时间:2016-04-02 08:03:19

标签: javascript jquery jstree

我知道这是用jstree jquery插件中的两个不同元素打开和关闭整个树的方法,如下所示:



$(document).ready(function () {

$treeview = $('#jstree-container');

    $treeview.jstree({
        "core": {
            'data': [
  {
    "id": 1,
    "text": "Root node",
    "children": [
      {
        "id": 2,
        "text": "Child node 1",
        "children": [
          {
            "id": 4,
            "text": "Child node 4"
          },
          {
            "id": 5,
            "text": "Child node 5"
          }
        ]
      },
      {
        "id": 3,
        "text": "Child node 2",
        "children": [
          {
            "id": 7,
            "text": "Child node 7"
          },
          {
            "id": 8,
            "text": "Child node 8"
          }
        ]
      }
    ]
  }
],
            "check_callback": true,
            "animation": 200,
            "dblclick_toggle": false,
            "themes": {
                responsive: true,
                "dots": true,
                "icons": true
            }
        },
        "plugins": ["checkbox", "dnd", "contextmenu", "search"],
        "search": {
            "show_only_matches": true,
            "show_only_matches_children": true
        },
        "checkbox": {
            "whole_node": false,
            "tie_selection": false //برا یاینکه با کلیک روی تکست گره ، چک باکس تیک نخوره
        }
    });



$('#collapse-all').click(function () {
  $treeview.jstree('close_all');
});
$('#expand-all').click(function () {
  $treeview.jstree('open_all');
});
  });

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.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>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet"/>

<a href="#" id="expand-all">open all</a>
|
<a href="#" id="collapse-all">close all</a>

<div id="jstree-container"></div>
&#13;
&#13;
&#13;

但是如何使用按钮打开和关闭整个树,以便在打开树时单击它并关闭它,如果它关闭,打开它?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。这是我应该使用的代码:

$treeview = $('#jstree-container');

    $('#expand-compress').click(function () {
        if ($('.jstree-open',$treeview).length){
            $treeview.jstree('close_all');
        }else{
            $treeview.jstree('open_all');
        }
    });