试图在 jstree 中的 change_state 上获取已检查项目的列表

2022-01-11 00:00:00 jquery jquery-plugins javascript jstree

使用 jsTree (pre1.0_fix_1),我想获取所有选中项目的 id 列表(或者更好的是,一个带有 id AND 每个选中项的文本).然后我会用这个进行ajax调用.此外,这应该在任何时候发生检查或取消检查的状态更改时发生.

Using jsTree (pre1.0_fix_1), I would like to obtain a list of id's for all the checked items (or better, a JSON object with id AND text of each checked item). I will then make an ajax call with this. Additionally, this should happen any time there is a state change of something getting checked or unchecked.

这是我目前拥有的:

$(function(){

  n = $('#colors').jstree({
    "plugins": ["themes", "html_data", "checkbox"]
  }).bind("change_state.jstree", function(e, data){
  console.log($('#colors').jstree('get_selected').attr('id'));
  });
});

这只是从容器的id返回'colors':<div id="colors">.我在 data 对象周围摸索了一下,但没有在其中找到它(也许我错过了它?)

This is just returning 'colors', from the container'sid: <div id="colors">. I fished around the data object, but didn't find it in there (perhaps I missed it?)

推荐答案

为了获得被检查节点的 JSON,你应该使用 get_checked 而不是 get_selected.试试这个:

In order to get the checked nodes' JSON you should be using get_checked and not get_selected. Try this:

    var checked = $("#colors").jstree("get_checked",null,true);
    var checked_json = [];
    $(checked).each(function (i,node) {
        var id = $(node).attr("id");
        var text = $(node).attr("text");
        var node_json = { 
            "id" : id, 
            "text" : text 
        };
        checked_json.push(node_json);
    });

之后,checked_json 将包含一组 id+text 对象,您可以将其发送到服务器.

After that checked_json will contain an array of of id+text objects which you could send to the server.

相关文章