为什么后续点击jstree的children不起作用

Why subsequent click on children of jstree does not work

我在使用 jstree 时遇到问题,一旦数据更改 click 将无法用于后续的每个 click,我需要 刷​​新页码 让它工作

这是 jsfiddle: http://jsfiddle.net/2Jg3B/2121/

我正在用如下新数据替换 jstree 设置数据

"data" :jsondata[index]

Note: please click on rendered child node

下面的Demo:(请使用jsfiddle查看完整http://jsfiddle.net/2Jg3B/2121/

var jsondata =  [
                [{
                    "data" : "A node 1",
                    "metadata" : { id : 123 },
                    "children" : [ "Child 11", "A Child 12" ]
                }],
                 [{
                    "data" : "A node 2",
                    "metadata" : { id : 223 },
                    "children" : [ "Child 21", "A Child 22" ]
                }],
                [{
                    "data" : "A node 3",
                    "metadata" : { id : 3223 },
                    "children" : [ "Child 31", "A Child 32" ]
                }]
            ]


function populateWithNewJsonData(index){
     $('#jstree').jstree({
        "json_data" : {
            "data" :jsondata[index]
        },
        "plugins" : [ "themes", "json_data", "ui" ]
    });
} 
var i = 0;
var intid = setInterval(function(){
   i++;
   if(i >= 3) i = 0;
   console.log('tree data changed',jsondata[i]);
   populateWithNewJsonData(i);
   $('p span#spannnnnnn').text(i);
},9000);


 $("#jstree").bind(
            "select_node.jstree",
            function(evt, data) {
          
              if (data.inst._get_parent().length <= 0 || data.inst._get_parent() === -1) {
                console.log('clicked data', data.inst.get_json());
              } else {
                console.log('clicked data',data.inst.get_json());
       }
 });
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://old.static.jstree.com/v.1.0pre/jquery.jstree.js"></script>
<p>
tree data changed with index : <span id="spannnnnnn"></span> data
</p>
<div id="jstree">
</div>

因为每次调用jstree方法时DOM都会被销毁并重新创建。所以你必须在创建新的 jstree 后再次分配监听器。旧的只是监听不再存在的节点上的点击事件。

将绑定 select_node.tree 事件侦听器的代码放入 addListener 函数中:

function addListener(){
     $("#jstree").bind("select_node.jstree", function(evt, data) {

          if (data.inst._get_parent().length <= 0 || data.inst._get_parent() === -1){
            console.log('clicked data', data.inst.get_json());
          } else {
            console.log('clicked data',data.inst.get_json());
          }
     });
}

创建函数以在销毁 jstree 之前删除侦听器:

function removeListeners(){
    $("#jstree").unbind("select_node.jstree");
}

使用它们:

function populateWithNewJsonData(index){
    removeListeners();

    $('#jstree').jstree({
        "json_data" : {
            "data" :jsondata[index]
        },
        "plugins" : [ "themes", "json_data", "ui" ]
    });
    addListeners();
} 

您可以在此 fiddle

中看到这些变化