jstree 复选框在加载时选中

发布于 2024-10-01 09:55:51 字数 1521 浏览 7 评论 0原文

我正在与 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;
        })

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

这个问题有帮助吗?

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:

.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.

Any help with this question?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

热风软妹 2024-10-08 09:55:51

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

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

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

{
  "data": "node name",
  "attr": { "id": "node id", "class":"jstree-checked" }
}
忆梦 2024-10-08 09:55:51

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

的配置

并添加到复选框部分“checkbox” :{
“tie_selection”:假
这个例子

工作正常

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

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

]

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

and add to config for checkbox section

"checkbox":{
"tie_selection": false
}

this example work fine

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

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

]
此生挚爱伱 2024-10-08 09:55:51

试试这个:

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

它对我有用。

以下是相关参考:

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

Try this:

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

It worked for me.

Here are related reference:

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

孤芳又自赏 2024-10-08 09:55:51

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

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

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

一切都很好:)

好运气好;)

I have found the solution by setting checkbox plugin option two_state to true

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

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

everything fine :)

good luck ;)

撞了怀 2024-10-08 09:55:51

为了完成上面的早期答案,至少使用最新的 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);

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.

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);
妥活 2024-10-08 09:55:51

也许这会对您有更多帮助 - 下面的 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>

事件绑定

<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>

- 用于检查和取消检查 jstree服务器端 Asp.net MVC 的

May be this will help you more - 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

<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

下雨或天晴 2024-10-08 09:55:51

"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"]
     });

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

 $('#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"]
     });
淡忘如思 2024-10-08 09:55:51

试试这个:

 $('#jstree').jstree({
      core : {
      data : [
        { "text" : "Root", state : { opened : true }, 
    children : [
            { "text" : "Child 1", state : { selected : true } },
            { "text" : "Child 2", state : { checked : false, opened : true }, 
    children : [
                { "text" : "a", state : { checked : true, opened : true }},
                { "text" : "b", state : { checked : false, opened : true }}
                
            ]}
            
        ]}
       ],
       },
      checkbox : {
       tie_selection : false  
       },
     plugins : ['checkbox']
    });

查找数据:

    var jsonNodes = $('#jstree').jstree(true).get_json('#', { flat: true });
    $.each(jsonNodes, function (i, val) {   
            if($("#jstree").find("a#" + this.id + "_anchor").hasClass("jstree-checked")){
                console.log("Selected:" + this.id);
                }
            else if($("#jstree").find("a#" + this.id + "_anchor i:first-child").hasClass("jstree-undetermined")){
                console.log("Selected:" + this.id);
                }
            else {
                console.log("Un Selected:" + this.id);
                }
        }

Try this:

 $('#jstree').jstree({
      core : {
      data : [
        { "text" : "Root", state : { opened : true }, 
    children : [
            { "text" : "Child 1", state : { selected : true } },
            { "text" : "Child 2", state : { checked : false, opened : true }, 
    children : [
                { "text" : "a", state : { checked : true, opened : true }},
                { "text" : "b", state : { checked : false, opened : true }}
                
            ]}
            
        ]}
       ],
       },
      checkbox : {
       tie_selection : false  
       },
     plugins : ['checkbox']
    });

Find data:

    var jsonNodes = $('#jstree').jstree(true).get_json('#', { flat: true });
    $.each(jsonNodes, function (i, val) {   
            if($("#jstree").find("a#" + this.id + "_anchor").hasClass("jstree-checked")){
                console.log("Selected:" + this.id);
                }
            else if($("#jstree").find("a#" + this.id + "_anchor i:first-child").hasClass("jstree-undetermined")){
                console.log("Selected:" + this.id);
                }
            else {
                console.log("Un Selected:" + this.id);
                }
        }
饮惑 2024-10-08 09:55:51

节点各项使用状态-> selected:true 或 false 来选中或不选中复选框。

// 节点的预期格式(没有必填字段)

{
  id          : "string" // will be autogenerated if omitted
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  children    : []  // array of strings or objects
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}

链接引用: https://www. jstree.com/docs/json/ ->转到“JSON 数据”选项卡

In each item of node use state -> selected: true or false to checked or not checkbox.

// Expected format of the node (there are no required fields)

{
  id          : "string" // will be autogenerated if omitted
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  children    : []  // array of strings or objects
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}

Link references: https://www.jstree.com/docs/json/ -> go to "JSON data" tab

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文