为什么我的 html 正文内容被覆盖而不是附加到?

问题描述 投票:0回答:1

我有以下脚本,我认为应该将有序的节列表附加到现有 html 正文的底部。但它正在取代它。为什么?


// Get all the sections
const sections = document.querySelectorAll('section.sections');

// Convert NodeList to an array for easier sorting
const sectionsArray = Array.from(sections);

// Sort sections based on the numeric value in their IDs
sectionsArray.sort((a, b) => {
    const idA = parseInt(a.id.replace('section', ''));
    const idB = parseInt(b.id.replace('section', ''));
    return idA - idB;
});

// Create a container to append the sorted sections
const container = document.createElement('div');

// Append sorted sections to the container
sectionsArray.forEach(section => {
    container.appendChild(section);
});

// Replace the original sections container with the sorted container
document.querySelector('body').appendChild(container);

javascript arrays dom
1个回答
0
投票

您在脚本中遇到的问题是,当您将现有 DOM 元素(如每个部分)附加到新的父元素(本例中为容器)时,它实际上将该元素从其原始位置移动到新位置。它不会创建它的副本。因此,当您运行脚本时,每个部分都会从文档中的原始位置删除并移动到新容器中。

由于您将此容器附加到正文而不删除或隐藏原始部分的容器,因此您仍然应该看到原始显示,除非原始部分位于外部(这不太可能)。但是,如果您的目的是将排序的部分与原始内容一起附加而不替换或移动原始部分,则您需要克隆每个部分而不是移动它们。以下是您可以修改脚本来克隆这些部分的方法:

// Get all the sections
const sections = document.querySelectorAll('section.sections');

// Convert NodeList to an array for easier sorting
const sectionsArray = Array.from(sections);

// Sort sections based on the numeric value in their IDs
sectionsArray.sort((a, b) => {
    const idA = parseInt(a.id.replace('section', ''));
    const idB = parseInt(b.id.replace('section', ''));
    return idA - idB;
});

// Create a container to append the sorted sections
const container = document.createElement('div');

// Append clones of sorted sections to the container
sectionsArray.forEach(section => {
    const clone = section.cloneNode(true);
    container.appendChild(clone);
});

// Append the container with cloned, sorted sections to the body
document.querySelector('body').appendChild(container);

此脚本将创建每个部分的克隆(包括所有子节点,因为使用了cloneNode(true))并将这些克隆附加到新容器,将原始部分保留在其初始位置。这样,您的原始部分保持不变,并且您可以有效地将一组新的排序部分添加到文档的末尾。

© www.soinside.com 2019 - 2024. All rights reserved.