javascript - 以编程方式在 JSTree 中创建文件夹结构
问题描述
当用户删除文件时,我正在尝试在 JSTree 中重新创建文件夹结构。假设用户删除文件路径为“A\B\XX”和“A\C\YY”的文件,我想在 jstree 中创建名称为 A、B 和 C 的节点。
截至目前,如果节点不存在,我可以添加它们。如果节点存在,我无法找到现有节点。在上面的示例中,我可以为 A 和 B 创建节点。但是第二次找不到节点“A”。
下面是我写到现在的代码。
var folderList = path.split("/");
for (var i = 0; i < folderList.length - 1; i++) { //-1 to remove the file name from the folder name list
var existingNodeID = '';
//Check if node already exists
var childrens = $("#js-tree").jstree("get_children_dom", parent);
for (var j = 0; j < childrens.length; j++) {
if (childrens[j].innerText == folderList[i]) {
existingNodeID = childrens[j].id;
}
}
//if node exists, select it as parent for the next loop
if (!(existingNodeID === '')) {
$('#js-tree').jstree().select_node(existingNodeID);
parent = $("#js-tree").jstree('get_selected', true)[0].original;
}
else {
//create a new node if there is no existing one
var newNode = {
id: generateUUID(),
text: folderList[i],
state: "open"
};
//Add node to jstree
var sel = $("#js-tree").jstree().create_node(parent, newNode);
//Select this node as parent for the next loop.
parent = newNode.id;
}
我基本上是拆分文件路径并为每个条目创建节点。此代码在所有文件的另一个循环中调用。
for (var i = 0; i < files.length; i++) {
//Add folder to JS Tree if it is not added
createTreeNodeFromFilePath(files[i].fullPath, parent);
}
parent
是树中的根节点。下面是查找现有兄弟的代码。
var childrens = $("#js-tree").jstree("get_children_dom", parent);
for (var j = 0; j < childrens.length; j++) {
if (childrens[j].innerText == folderList[i]) {
existingNodeID = childrens[j].id;
}
}
显然这永远找不到任何兄弟姐妹。假设我已经有一个节点“A”,并且我有“A”的父节点的 id,那么这段代码应该能够让我得到节点“A”的 id。
编辑:
更新了代码。下面是一个快速的 TL;DR。
如果节点“A”有子节点“B”和“C”,我想遍历“A”的那些子节点并根据名称选择节点。
解决方案
最终想通了一个警告。
//get list of all children of current parent node. returns an array of ids.
var childrens = $("#js-tree").jstree("get_node", parent).children_d;
//check if childrens exist
if (childrens) {
//loop through the children list to find the existing child node with same name
for (var j = 0; j < childrens.length; j++) {
if ($("#js-tree").jstree("get_node", childrens[j]).text == folderList[i]) {
existingNodeID = childrens[j];
}
}
children_d
给我一个所有子节点的 id 列表。然后在循环内,我get_node
再次使用来获取实际的节点引用。这工作正常,并允许我遍历所有子节点以查看它们是否存在。其余代码与问题无关。
现在警告一下。该children_d
属性也返回子节点的所有子节点。所以,如果我有 1\2\3\4 作为树,children_d
节点 1 将返回[2,3,4]
. 基本上,不仅仅是子节点,它还遍历整个子树,就像子节点的子节点一样。
这不应该是一个大问题,因为它只是不必要的循环。但是如果文件夹中有同名的文件夹,那么我会创建额外的节点。因此, 1\2\1\xx 有效。但是 1\1\2\1\xx 不起作用。
无论如何,这完全是一个不同的问题,我现在可以推迟。
推荐阅读
- python - 使用python解压缩.Z文件时出错
- listview - BindCommand 与参数 ListView ReactiveUI Xamarin 表单
- java - 命令“javac -h”和“javah -jni”找不到我指定的文件
- oracle - 如何正确映射 MyBatis 父关系?
- python - python如何为列表和字符串分配内存?
- python - 在 python 类中,我应该如何从同一类的另一个方法调用该类的非实例方法?
- javascript - 模糊除css中选定区域以外的所有图像
- html - 是否可以将大图像完美地放入较小的 div 中?
- javascript - 在 papaparse 完成之前,如何防止我的代码继续执行?
- asp.net-core - 在 ASP.NET Core 中启用跨域请求 (CORS)(文件上传)