jQuery 加载时选中 jstree 复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4128607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:43:06  来源:igfitidea点击:

jstree checkbox checked on load

jqueryuser-interfacejquery-pluginsjstree

提问by ignas

I'm fighting with jQuery jsTree plugin checkbox. Ok, I have find out how to handle events on checking or unchecking checkbox. If its useful I can paste a code:

我正在与 jQuery jsTree 插件复选框作斗争。好的,我已经找到了如何处理选中或取消选中复选框的事件。如果有用,我可以粘贴代码:

.bind("check_node.jstree", function(e, data)
        {

            if(data.rslt.obj !== undefined && data.rslt.obj.attr(\'id\') !== undefined)
            {

                jQuery.ajax({
                        async : false,
                        type: "POST",
                        dataType: "json",
                        url: "adsmanager/adsfields/ajaxappendcategory",
                        data:
                        {
                            "id" : data.rslt.obj.attr(\'id\'),
                            "itemId" : "' . Yii::app()->getRequest()->getParam('id') . '",
                        },
                        success: function(r)
                        {
                            if(r === undefined || r.status === undefined || !r.status)
                            {
                                data.rslt.obj.removeClass(\'jstree-checked\');

                                data.rslt.obj.addClass(\'jstree-unchecked\');

                            }
                            else
                            {
                                niceBox(\'ok\');
                            }
                        }
                    });

            }

            return true;
        })

With this everything is ok, but know I cant find anywhere how to checked checkboxes on tree load, for example, if I'm using jsTree like category selector for my news Item when I create new news item everything is ok and when I want to update that item I need jsTree with selected categories and that's I cant find any example how to select nodes on loading jsTree.

有了这个,一切都好了,但我知道我无法在任何地方找到如何在树加载时选中复选框,例如,如果我在创建新新闻项目时使用 jsTree 之类的类别选择器作为我的新闻项目,那么一切都很好,当我想更新我需要使用选定类别的 jsTree 的项目,那就是我找不到如何在加载 jsTree 时选择节点的任何示例。

Any help with this question?

这个问题有什么帮助吗?

回答by Trick

If you are using JSON_DATA, add class:jstree-checkedto the node's attr object:

如果您使用 JSON_DATA,请添加class:jstree-checked到节点的 attr 对象:

{
  "data": "node name",
  "attr": { "id": "node id", "class":"jstree-checked" }
}

回答by Developer

For current JSTREE version 3.2.1 and JSON data we need use state : { checked : true }

对于当前的 JSTREE 版本 3.2.1 和 JSON 数据,我们需要使用 state : { checked : true }

and add to config for checkbox section

并添加到复选框部分的配置

"checkbox":{ "tie_selection": false }

“复选框”:{“tie_selection”:假}

this example work fine

这个例子工作正常

data : [
            { "text" : "Root", state : { opened : true }, children : [

                { "text" : "Child 2", state : { checked : true },

]

回答by alysonsm

Try this:

尝试这个:

$("#jstree").jstree(true).load_node('#');

It worked for me.

它对我有用。

Here are related reference:

以下是相关参考:

https://groups.google.com/forum/#!topic/jstree/bPv19DwQYFU

https://groups.google.com/forum/#!topic/jstree/bPv19DwQYFU

回答by ignas

I have found the solution by setting checkbox plugin option two_stateto true

我通过将复选框插件选项设置two_state为 true找到了解决方案

"checkbox" => array(  "two_state" => true)

and then if you are using Xml data add class="jstree-checked"in params

然后如果您使用 Xml 数据添加class="jstree-checked"参数

everything fine :)

一切都很好 :)

good luck ;)

祝你好运 ;)

回答by Jahirul Islam Bhuiyan

May be this will help you more - jstree v1

可能这会帮助你更多 - jstree v1

<script src="@Url.Content("~/Scripts/jquery.jstree.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.cookie.js")" type="text/javascript"></script>

below - for check and uncheck event bind for jstree

下面 - 用于检查和取消选中 jstree 的事件绑定

<script type="text/javascript">
        $(document).ready(function () {
            Refresh();
        });

        function Refresh() {
            var dataId = {};
            $('#MainTree')
              .bind("before.jstree", function (e, data) {
              })
            .jstree({

                "json_data": {
                    ajax: {

                        "url": function (node) {
                            var url;
                            if (node == -1) {
                                url = "";
                            } else {
                                var id = $(node).data("id");
                                url = "?categoryId=" + id;
                            }
                            var productId = $("#Product_ProductId").val();
                            if (!productId) {
                                url = "/Products/GetTreeData" + url;
                            } else {
                                url = "/Products/GetTreeData/" + productId + url;
                            }
                            return url;
                        },

                        //"url": "@Url.Action("GetTreeData", "Categories")",
                        "type": "GET",
                        //"data": JSON.stringify(dataId),
                        "dataType": "json",
                        "contentType": "application/json charset=utf-8",
                    },
                    progressive_render: true
                },
                "themes": {
                    "theme": "classic",
                    "dots": true,
                    "icons": true,
                    "url": "@Url.Content("~/content/themes/classic/style.css")"
                },
                "types": {
                    "max_depth": -2,
                    "max_children": -2,
                    "valid_children": ["folder"],
                    "types": {
                        "default": {
                            "valid_children": "none",
                            "icon": {
                                "image": "@Url.Content("~/gfx/file.png")"
                            }
                        },
                        "folder": {
                            "valid_children": ["default", "folder"],
                            "icon": {
                                "image": "@Url.Content("~/gfx/folder.png")"
                            }
                        }
                    }
                },
                "plugins": ["themes", "json_data", "ui", "types", "checkbox"]

            })
            .bind("load_node.jstree", function (event, data) { 

                var productId = $("#Product_ProductId").val();
                if (!productId || productId < 1) {
                    data.inst.hide_checkboxes();
                } else
                    data.inst.change_state('li[selected=selected]', false);
            })
            .bind("check_node.jstree", function (e, data) {
                var productId = $("#Product_ProductId").val();
                if (!productId)
                    return;
                $.post(
                    "@Url.Action("ProductCategoriesSaveData", "Products")",
                    {
                        "ProductCategory.ProductId": productId,
                        "ProductCategory.CategoryId": $(data.rslt.obj).data("id")
                    },
                    function (r) {

                        //Display message if any
                        if (r.Message) {
                            alert(r.Message);
                        }

                        //Display error if any
                        if (r.ValidationError) {
                            $.jstree.rollback(data.rlbk);
                            alert(r.ValidationError);
                        } else {
                            if (r.NewCreatedId) {
                                $(data.rslt.obj).data("mapId", r.NewCreatedId);
                            }
                        }
                    });
            })
            .bind("uncheck_node.jstree", function (e, data) {
                var productId = $("#Product_ProductId").val();
                if (!productId)
                    return;
                var mapId = $(data.rslt.obj).data("mapId");
                $.ajax({
                    async: false,
                    type: 'POST',
                    url: "@Url.Action("ProductCategoryDelete", "Products")",
                    data: {
                        "id": mapId
                    },
                    success: function (r) {
                        //Display message if any
                        if (r.Message) {
                            alert(r.Message);
                        }

                        //Display error if any
                        if (r.ValidationError) {
                            alert(r.ValidationError);
                        } else {
                            data.inst.refresh();
                        }
                    }
                });
            });
        }
    </script>

Server side Asp.net MVC

服务器端 Asp.net MVC

回答by Waqas Bukhary

"state" : { "selected" : true }Makes a checkbox selected

"state" : { "selected" : true }选中一个复选框

 $('#frmt').jstree( { 
        'core' :  {
            'data' : [{ 
                    "text" : "root text",
                    "state" :  {  "opened" : true  } ,
                    "children" : [{ 
                            "text" : "child text",
                            "id" : "idabc",
                            "state" :  {  "selected" : true  } ,
                            "icon" : "jstree-file",

                    }]
                 },

            ]},
            'checkbox': {
                      three_state: true
             },
            'plugins': ["checkbox"]
     });

回答by energy

To complete earlier answers above, with latest v3.3.7 at least, the specification of BOTH state.selected and a_attr.class are required for a leaf checkbox to be initialized as checked with the checkbox plugin. This seems to explain why mytree.node_select("leafId") function alone does not accomplish this programatically, presumably because the child a class attribute also has to be set to jstree_checked.

要完成上述较早的答案,至少在最新的 v3.3.7 中,需要指定 state.selected 和 a_attr.class 才能将叶复选框初始化为使用复选框插件进行检查。这似乎解释了为什么 mytree.node_select("leafId") 函数不能以编程方式完成这一点,大概是因为子类属性也必须设置为 jstree_checked。

var mytree = $( "myjstreediv" ).jstree();
var leafParentId = "#";
var name = "My test node";
var visible = true;
if (visible)
   leafId = mytree.create_node(leafParentId, {
      text: name, 
      state: { selected: visible }, 
      a_attr: { class: "jstree-checked" } 
   });
else
   leafId = mytree.create_node(leafParentId, name);