首页 > 解决方案 > 将 document.createElement('div') 更改为 document.createDocumentFragment()

问题描述

const allItemContainer = document.getElementById("all-items");
data.pizza.forEach((item) => {
        let container = document.createElement("div");
        //container will contain <div class='shop-item'>
        container.classList.add("shop-item");
        container.id = item.id; //will add an id to the current div equal to the ID given in the json file
        let textHeading = document.createElement("span");
        textHeading.classList.add("shop-item-title");
        textHeading.appendChild(document.createTextNode(item.name));
}
container.appendChild(textHeading);
allItemContainer.appendChild(container);
});

我希望将其更改document.createElement()document.createDocumentFragment(). 我尝试更改它,但出现错误:- Uncaught (in promise) TypeError: Cannot read property 'add' of undefined 如何将 classList 添加到此 Fragment?我是新手。请帮忙。

标签: javascriptdom

解决方案


由于性能原因,我想转移到片段

您的代码无效,但我认为allItemContainer.appendChild(container);调用在forEach回调中。如果是这样,并且如果添加这些元素确实会导致性能问题,那么您可以通过将每个容器添加到片段并在末尾插入片段以仅导致单个回流(而不是为每个容器):

const allItemContainer = document.createDocumentFragement();

data.pizza.forEach((item) => {
    let container = document.createElement("div");
    //container will contain <div class='shop-item'>
    container.classList.add("shop-item");
    container.id = item.id; //will add an id to the current div equal to the ID given in the json file
    let textHeading = document.createElement("span");
    textHeading.classList.add("shop-item-title");
    textHeading.appendChild(document.createTextNode(item.name));
    container.appendChild(textHeading);
    allItemContainer.appendChild(container);
});

document.getElementById("all-items").appendChild(allItemContainer);

推荐阅读