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

toggle entire tree only by a simple button in 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>

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

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

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

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