javascript 修改列表中列出项目的代码

zpgglvta  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(106)

我在points元素中有这样一个项目。

<body>
Parent 1
Parent 2
Parent 3
    1st Child of 3
        1st grandchild
        2nd grandchild
    2nd Child of 3
    3rd Child of 3
Parent 4
    Parent 4's only child
</body>

我需要使用JavaScript生成这样一个有效的列表。

<ul class="tree">
    <li>Parent 1</li>
    <li>Parent 2</li>
    <li> Parent 3
        <ul>
            <li> 1st Child of 3
                <ul>
                    <li>1st grandchild</li>
                    <li>2nd grandchild</li>
                </ul>
            </li>
            <li>2nd Child of 3</li>
            <li>3rd Child of 3</li>
        </ul>
    </li>
    <li> Parent 4
        <ul>
            <li>Parent 4's only child</li>
        </ul>
    </li>
</ul>

我尝试了这样的代码,但代码仍然不起作用。

var bodyElement = document.body;
var bodyText = bodyElement.textContent;
bodyElement.textContent = '';
var outputDiv = document.createElement('div');
outputDiv.id = 'output';
document.body.appendChild(outputDiv);
var outputElement = document.getElementById('output');
var lines = bodyText.split('\n');
var ul = document.createElement('ul');
ul.classList.add('tree'); // Přidáme třídu "tree" k ul elementu
var currentUl = ul;
var currentLi = null;
for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var indent = line.match(/^\t*/)[0].length; // Zjistíme počet tabulátorů na začátku řádku
    var li = document.createElement('li');
    var span = document.createElement('span');
    span.textContent = line.trim(); // Odstraníme bílé znaky na začátku a konci řádku
    li.appendChild(span);
    if (indent === 0) {
        if (currentLi) {
            currentUl.appendChild(currentLi);
        }
        currentLi = li;
        ul.appendChild(currentLi);
        currentUl = document.createElement('ul');
        currentLi.appendChild(currentUl);
    } else {
        if (currentLi) {
            currentUl.appendChild(currentLi);
        }
        currentLi = li;
    }
}
if (currentLi) {
    currentUl.appendChild(currentLi);
}
outputElement.appendChild(ul);

我尝试了不同的变体,但我根本无法让它工作。

isr3a4wc

isr3a4wc1#

通常使用堆栈来跟踪缩进。

let li = document.body, ul;
const stack = [-1];
for (const line of document.body.firstChild.textContent.match(/.*\S/g)) {
    const indent = line.length - line.trim().length;
    while (stack.at(-1) >= indent) {
        stack.pop();
        li = li.parentNode.parentNode;
    }
    li.appendChild(ul = li.querySelector("ul") ?? document.createElement("ul"));
    ul.appendChild(li = document.createElement("li"));
    li.textContent = line.trim();
    stack.push(indent);    
}
document.body.firstChild.remove();
document.body.querySelector("ul").classList.add("tree");
.tree { background: pink }
Parent 1
Parent 2
Parent 3
    1st Child of 3
        1st grandchild
        2nd grandchild
    2nd Child of 3
    3rd Child of 3
Parent 4
    Parent 4's only child

相关问题