【问题标题】:prevent jsTree node select防止jsTree节点选择
【发布时间】:2014-06-28 23:06:17
【问题描述】:

我正在使用 jsTree 插件来列出文件系统中的文件夹。我需要防止用户在满足某个条件之前更改到另一个节点。
下面的代码不会停止传播......我看到了一些使用其他插件的解决方案,但这是一个简单的任务,它必须在没有其他插件的情况下成为可能。

$('#jstree').on('select_node.jstree', function (e) 
{
    if (!changeAllowed()
    {
        e.preventDefault(); 
        e.stopImmediatePropagation();
    }
}); 

【问题讨论】:

    标签: jquery jquery-plugins jstree


    【解决方案1】:

    为我自己和后代记录:您需要在加载 jstree JS 之后包含以下函数(来自:https://github.com/vakata/jstree/blob/master/src/misc.js):

    // jstree conditional select node
    (function ($, undefined) {
      "use strict";
      $.jstree.defaults.conditionalselect = function () { return true; };
    
      $.jstree.plugins.conditionalselect = function (options, parent) {
        // own function
        this.select_node = function (obj, supress_event, prevent_open) {
          if(this.settings.conditionalselect.call(this, this.get_node(obj))) {
            parent.select_node.call(this, obj, supress_event, prevent_open);
          }
        };
      };
    })(jQuery);
    

    然后在初始化 jstree 的实例时执行以下操作:

    $('#jstree').jstree({
      'conditionalselect' : function (node) {
        return <something that determines condition> ? true : false;
      },
      'plugins' : ['conditionalselect'],
      'core' : {
        <core options>
      }
    });
    

    【讨论】:

    • 这有一个错误。假设树只允许选择 1 个选项,并且您选择 A,然后选择 B,并且“条件”拒绝 B。您希望 A 仍然被选中,但事实并非如此。