javascript - 将 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?我是新手。请帮忙。
解决方案
由于性能原因,我想转移到片段
您的代码无效,但我认为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);
推荐阅读
- java - [已解决]Spring boot:在进行 post 请求时如何将子级保存在现有父级中
- c# - IMutableEntityType.GetProperties() 不包含我想要的属性
- json - 在所需的 JSON 参数中包装和编组 Go 结构
- vue.js - Axios CORS 问题 Consuming API
- python - 使用一个 Flask 路由将来自 BigQuery 的多个查询返回到 html 表中
- kubernetes - 为什么 client.Update(...) 会忽略非原始值?
- vb.net - 向后搜索文件夹中的文件
- flutter - 如何使 ListView 项目在具有固定高度的容器底部对齐,而不在 Flutter 中使用反向?
- c# - ASP.Net Core + .NET Framework Web API - 频繁的网络错误
- android - AutoCompleteTextView - 在弹出窗口可见时旋转设备时崩溃