You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue2中从HTML元素生成树形结构时子元素ID缺失的修复方案

修复树形结构ID提取问题

你的代码里有两个关键错误导致ID=12的元素没被正确抓取:

错误1:选择器拼写错误

在获取ID时,你写了 child.querySelector(".plan-element"),但HTML中目标元素的类名是 single-element,这个拼写错误会导致无法获取到元素,ID自然为空。

错误2:Type属性获取位置错误

child.getAttribute("type") 是从外层包裹的<div>取type属性,但实际type属性是定义在.single-element元素上的,所以这里取到的永远是null。

修复后的函数代码

buildDraggedHierarchy(el) {
    if (!el) {
        return [];
    }

    const children = [...el.querySelectorAll(":scope>div")];
    const output = children.map((child) => {
        const singleElement = child.querySelector(".single-element");
        return {
            id: singleElement ? singleElement.id : null, 
            type: singleElement ? singleElement.getAttribute("type") : null, 
            children: this.buildDraggedHierarchy(child.querySelector(".draggable-container")), 
        };
    });

    return output;
}

修复后的输出结果

[
    {
        "id": "2",
        "type": "elementType",
        "children": [
            {
                "id": "59",
                "type": "elementType",
                "children": []
            }
        ]
    },
    {
        "id": "3",
        "type": "elementType",
        "children": [
            {
                "id": "13",
                "type": "elementType",
                "children": []
            },
            {
                "id": "14",
                "type": "elementType",
                "children": []
            }
        ]
    },
    {
        "id": "11",
        "type": "elementType",
        "children": [
            {
                "id": "12",
                "type": "elementType",
                "children": []
            }
        ]
    }
]

这样修改后,不仅ID=12的元素能正确显示,所有元素的type属性也能正确获取到了。

内容的提问来源于stack exchange,提问作者Yellow rain coat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 14:19:57