简体   繁体   中英

How “id” works in populating jsTree using JSON

I am using the alternative JSON format to populate my jsTree as shown in this link.

The problem is I can't find how the "id" attribute works in jsTree?

In my case, both the parents can have same names sometimes. (Its not ideal but its a rare scenario that pops up so i have to handle it). So i use their unique "id's" in the tree. Now if the childern nodes of the parents have the same "id" as parent nodes, somehow the jsTree does not work on button click and keeps showing the "Loading.." message.

My JSON:

[
  {
    "id": "3",         //Any value except 3 and 5 works
    "text": "Ford",
    "parent": "3",
    "icon": "fa fa-circle-o"
  },
  {
    "id": "5",        //Any value except 3 and 5 works
    "text": "Fiat",
    "parent": "5",
    "icon": "fa fa-circle-o"
  },
  {
    "id": "3",
    "text": "Cars",
    "parent": "#",
    "icon": "glyphicon glyphicon-triangle-right"
  },
  {
    "id": "5",
    "text": "Cars",
    "parent": "#",
    "icon": "glyphicon glyphicon-triangle-right"
  }
]

My html code:

 <div id="car-list" class="collapse">
                       #{MyBean.jsonString}
                   </div>
                   <h:outputScript>
                       $(function() {
                           var data1= JSON.parse(document.getElementById("car-list").innerHTML);
                           $('#car-list').jstree({
                               'core': {
                                   'data': data1
                               }
                           });
                       });
                   </h:outputScript>

where jsonString is a String object containing the above json

In jstree every time I had 2 identical keys I could see only one element rendered instead of 2 (talking about the elements with the identical keys). In your case I imagine that the problem is that you have loops in your nodes so the rendering never ends. I surpassed my problem by creating keys from concatenation (parentKey_childKey). So in your case this would be:

[
  {
    "id": "3_3",         
    "text": "Ford",
    "parent": "3",
    "icon": "fa fa-circle-o"
  },
  {
    "id": "5_5",        
    "text": "Fiat",
    "parent": "5",
    "icon": "fa fa-circle-o"
  },
  {
    "id": "3",
    "text": "Cars",
    "parent": "#",
    "icon": "glyphicon glyphicon-triangle-right"
  },
  {
    "id": "5",
    "text": "Cars",
    "parent": "#",
    "icon": "glyphicon glyphicon-triangle-right"
  }
]

You can also see that multiple nodes with identical keys is not supported here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM