jstree-阻止单个扩展节点崩溃

时间:2018-11-12 16:01:31

标签: javascript jquery tree jstree

使用jstree是否可以阻止单个特定节点的崩溃?

我有一个可以随意扩展/折叠的树结构...但是我有某些节点应该始终打开,并且不允许用户折叠它们。

是否有一种方法来阻止折叠(可能通过data-jstree上的<li>属性),并且如果可能的话,还可以去除该项目上的三角形?

我已经尝试挂接到close_node.jstree事件,但是使用return falsee.preventDefault()都不能阻止该事件的发生。

在下面的示例中,我希望始终打开“项目2-必须保持打开”,并且不允许用户隐藏“始终可见”项目...

$(function() {
  $("#treeRoot").jstree({
    core: {
      themes: {
        variant: "small"
      }
    }
  });
});
<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="treeRoot">
  <ul>
    <li data-jstree='{"opened":true}'>Root
      <ul>
        <li>Item 1</li>
        <li data-jstree='{"opened":true}'>Item 2 - Must keep open
          <ul>
            <li>Always Visible</li>
          </ul>
        </li>
        <li>Item 3</li>
      </ul>
    </li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:1)

除了覆盖jstree代码的close_node函数的选项之外,我找不到阻止节点关闭的任何选项。

这里是一个例子:

$(function() {

  $.jstree.core.prototype.old_close_node = $.jstree.core.prototype.close_node;
  $.jstree.core.prototype.close_node = function(obj, animation) {
    node_obj = this.get_node(obj);
    // in case the flag exists - don't continue to with the original function.
    if (node_obj.state.prevent_close) {
      return;
    }
    this.old_close_node(obj, animation);
  }
  
  $("#treeRoot").on('loaded.jstree', function() {
    $('#treeRoot li').each((index, el) => {
      if ($(el).data('jstree') && $(el).data('jstree').prevent_close) {
        $(el).addClass('prevent-close');
      }
    })
  }).jstree({
    core: {
      themes: {
        variant: "small"
      }
    }
  })
});
.jstree-default-small .jstree-open.prevent-close>.jstree-ocl {
  background-position: -71px -7px;
}
<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="treeRoot">
  <ul>
    <li data-jstree='{"opened":true}'>Root
      <ul>
        <li>Item 1</li>
        <!--                             v-- this is the flag to prevent the close -->
        <li data-jstree='{"opened":true, "prevent_close": true}'>Item 2 - Must keep open
          <ul>
            <li>Always Visible</li>
          </ul>
        </li>
        <li>Item 3</li>
      </ul>
    </li>
  </ul>
</div>

我没有时间处理三角形,如果您有问题,请告诉我,我也将尝试为该三角形找到解决方案。