首页 > 解决方案 > 以编程方式在 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”的那些子节点并根据名称选择节点。

标签: javascriptjstree

解决方案


最终想通了一个警告。

//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 不起作用。

无论如何,这完全是一个不同的问题,我现在可以推迟。


推荐阅读