我需要填充我的 jsTree 并在选择我能够做到的 jsTree 的任何节点时触发一些 ajax 调用。但问题是我必须重新填充同一棵树并再次触发该 ajax 调用。重新填充后,我无法在选择任何树节点时触发 SELECT 或 CLICK NODE 事件。下面是代码。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript"
src="//static.jstree.com/3.2.1/assets/dist/jstree.min.js"></script>
<link rel="stylesheet"
href="//static.jstree.com/3.2.1/assets/dist/themes/default/style.min.css" />
<script>
$(document).ready(function(){
$("#tree").on("select_node.jstree", function(event, node) {
$("#para").text("");
var selected = node.instance.get_selected();
if(selected.length === 1) {
$("#para").text(selected[0]); // Here goes my ajax call.
} else if(selected.length > 1) {
alert("hi");
}
});
});
function getData(){
$('#tree').jstree("destroy").empty();
$('#tree').jstree({
'core' : {
'data' : [
{ "id" : "ajson1", "parent" : "#", "text" : "Root node1" },
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
]
}
});
}
</script>
</head>
<body>
<a id="go" href="#" onclick="getData()">Get Tree</a><br><br><br><br>
<div id="tree"></div>
<p id="para"></p>
</body>
</html>
您可以将此代码直接粘贴到w3school站点并进行测试。无法制作 jsFiddle。
最佳答案
创建一个单独的函数来添加事件监听器。然后从 Doc ready 以及 getData() 末尾调用该函数。喜欢
$(document).ready(function(){
function addEventListener(){
$("#tree").on("select_node.jstree", function(event, node) {
$("#para").text("");
var selected = node.instance.get_selected();
if(selected.length === 1) {
$("#para").text(selected[0]); // Here goes my ajax call.
} else if(selected.length > 1) {
alert("hi");
}
});
}
addEventListener();
function getData(){
$('#tree').jstree("destroy").empty();
$('#tree').jstree({
'core' : {
'data' : [
{ "id" : "ajson1", "parent" : "#", "text" : "Root node1" },
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
]
}
});
addEventListener();
}
})
关于javascript - 如何在重新填充 jsTree 后触发它的选择节点事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36085384/