如何在动态树中以编程方式选择子节点?
-
26-09-2019 - |
题
我在应用程序中使用 jQuery 的 dynaTree,并且希望在选择父节点时以编程方式选择所有子节点。我的树的结构如下
<div id = "tree">
<ul>
<li>package 1
<ul>
<li>module 1.1
<ul>
<li> document 1.1.1</li>
<li> document 1.1.2</li>
</ul>
</li>
<li>module 1.2
<ul>
<li>document 1.2.1</li>
<li>document 1.2.2</li>
</ul>
</li>
</ul>
</li>
<li> package 2
<ul>
<li> module 2.1
<ul>
<li>document 2.1.1</li>
<li>document 2.1.1</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
现在我想要的是,当我单击标题为“package 1”的树节点时,它的所有子节点即(模块 1.1、文档 1.1.1、文档 1.1.2、模块 1.2、文档 1.2.1、文档 1.2.2)也应该选择。
以下是我尝试使用的方法:
$("#tree").dynatree({
onSelect: function(flag, dtnode) {
// This will happen each time a check box is selected/deselected
var selectedNodes = dtnode.tree.getSelectedNodes();
var selectedKeys = $.map(selectedNodes, function(node) {
//alert(node.data.key);
return node.data.key;
});
// Set the hidden input field's value to the selected items
$('#SelectedItems').val(selectedKeys.join(","));
if (flag) {
child = dtnode.childList;
alert(child.length);
for (i = 0; i < child.length; i++) {
var x = child[i].select(true);
alert(i);
}
}
},
checkbox: true,
onActivate: function(dtnode) {
//alert("You activated " + dtnode.data.key);
}
});
在里面 if(flag)
条件我得到了用户选择的元素的所有子节点,它给了我可以从alert(child.length)语句中看到的正确值。然后我运行循环来选择所有子项,但循环永远不会超出语句 var x = child[i].select(true);
我永远看不到声明 alert(i)
正在被处决。上述语句的结果是,如果我选择包 1,则模块 1.1 和文档 1.1.1 也被选择,但它永远不会执行 alert(i)
声明 - 没有选择包 1 的其他子项。在我看来,当第一次 child[i].select(true)
语句执行时它还会触发其子级的 on select 事件,从而形成递归之类的事情
我的想法正确吗?无论什么递归或它到底做了什么,它都不会完成循环并执行下一条指令 alert(i)
.
请帮助我解决这个问题。我非常希望看到这种警报,任何建议和帮助都将受到高度赞赏。
解决方案
勉强测试,但你可以尝试这样的事:
$(function(){
var inEventHandler = false;
$("#tree").dynatree({
checkbox: true,
selectMode: 2,
[...]
onSelect: function(select, dtnode) {
// Ignore, if this is a recursive call
if(inEventHandler)
return;
// Select all children of currently selected node
try {
inEventHandler = true;
dtnode.visit(function(childNode){
childNode.select(true);
});
} finally {
inEventHandler = false;
}
}
其他提示
虽然我不是 Dynatree 内部功能的专家,但我编写了一些代码,为单击的节点及其所有后代生成面包屑。
在下面的示例中,单击“edibles”将输出:
edibles
edibles > fruits
edibles > fruits > apples
edibles > fruits > apples > green apples
edibles > fruits > apples > green apples > granny smith
edible > vegetables
edible > vegetables > potatoes
点击“青苹果”时会输出:
edibles > fruits > apples > green apples
edibles > fruits > apples > green apples > granny smith
您可以从此示例中汲取灵感,从所有子文档中检索所需的字段并生成 HTML 输出。
代码在此线程中:从具有 3 列(id、路径、名称)的 PHP 数组生成文本面包屑的最佳方法?
PHP 脚本本身是通过 Dynatree 的 onActivate 事件处理程序调用的 jQuery.ajax({...});
询问。
使用代替从 mar10的答案之一的以下功能。
全部子节点被选择/取消选择父节点上选择/取消选择。
onSelect: function (isSelected, node) {
node.visit(function (childNode) {
childNode.select(isSelected);
});
},