首页 > 解决方案 > 在检查事件中获取 jstree 中的所有选定节点?

问题描述

我正在使用 get_bottom_selected 来获取 JSTree 中所有选中/选中的节点。当我在表单中设置一个调用以下方法的按钮时,它可以工作。当我尝试从复选框单击事件中调用相同的函数时,即使有一些节点,它也找不到任何选定的节点。

function testit() {
    var data = $('#my_tree').jstree(true).get_bottom_selected(true);
    for(var count = 0; count < data.length; count++){
        // Do Stuff 
    }
}

当以下事件触发时,我想调用该函数并获取所有选定的子节点,但它不起作用。在此事件上是否有与从按钮单击事件调用不同的特定操作?

.on("check_node.jstree uncheck_node.jstree", function(e, data) {
            testit(); // first line of this function does not get any selected data, even if several are selected. When called from a button click event in my form it does work. 
            });

这是我目前的 jstree 设置方式。

$('#my_tree')
.on("changed.jstree", function (e, data) {
    // Do Stuff
})
.jstree({
checkbox: {
    "keep_selected_style": false,
    "visible" : true,
    "three_state": true,
    "whole_node" : true,
},
plugins: ['checkbox'],
    'core' : {
    'multiple' : true,
    'data' : {
    "url" : "/static/content_data.json",
    "dataType" : "json" 
    }
}
})
.on("check_node.jstree uncheck_node.jstree", function(e, data) {
    testit();
});

标签: javascripthtmljstree

解决方案


由于严格模式,如果您尝试使用 get_bottom_checked,您将遇到异常

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them. at Function.invokeGetter (<anonymous>:2:14)

如果您只需要选定节点的 ID,则可以data.selected从检查或取消检查事件处理程序中使用,但如果您需要更多,则可以使用“data.instance._model.data”。正如您在我的示例中看到的那样,如果只选择了一项并且该状态处于打开状态,我会尝试提醒您。在代码示例中,如果您打开 `Europe1 并选中复选框,则可以看到警报。

var data1 = [{
  "id": "W",
  "text": "World",
  "state": {
    "opened": true
  },
  "children": [{
      "text": "Asia"
    },
    {
      "text": "Africa"
    },
    {
      "text": "Europe",
      "state": {
        "opened": false
      },
      "children": ["France", "Germany", "UK"]
    }
  ]
}];

function testit(data) {
  alert(data.length + ' and ids are ' +data );
  for (var count = 0; count < data.length; count++) {

  }
  
}
$('#Tree').jstree({
  core: {
    data: data1,
    check_callback: false
  },
  checkbox: {
    three_state: false, // to avoid that fact that checking a node also check others
    whole_node: false, // to avoid checking the box just clicking the node 
    tie_selection: false // for checking without selecting and selecting without checking
  },
  plugins: ['checkbox']
})
$('#Tree').on("check_node.jstree uncheck_node.jstree", function(e, data) {
 if (data.selected.length === 1) { alert(data.instance._model.data[data.selected].state['opened']); }
  testit(data.selected);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" type="text/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="Tree"></div>


推荐阅读