浏览器与 Web API / 系统课时
从数组渲染列表
从数组渲染列表
列表渲染的核心不是把字符串拼成 HTML,而是把每条数据稳定地映射为一个节点。本课遍历数组创建列表项,先放入 DocumentFragment,再一次性更新容器,并通过页面与控制台结果验证数据、节点和状态是否一致。
学习目标
- 将数组中的每个对象转换为对应的列表项节点。
- 使用
DocumentFragment在内存中集中组装节点。 - 验证一次性插入后的 DOM 内容与界面状态。
从数组到节点的渲染链路
渲染过程可以拆成四步:读取一条数据、创建节点、写入属性与文本、加入临时片段。循环结束后,再把整个片段交给列表容器。这样数据映射逻辑集中在一个位置,也避免在循环中反复改动真实容器。
DocumentFragment 只是临时载体。执行 list.replaceChildren(fragment) 后,片段中的子节点会被移动到 ul,片段自身重新变为空。它不会在最终 DOM 中形成额外包裹层。

完整列表渲染示例
下面的完整页面把任务数组渲染为只读清单。replaceChildren 会先清空旧内容,再接收片段中的全部节点,适合执行一次完整刷新。
html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>数组列表渲染</title>
</head>
<body>
<ul id="task-list"></ul>
<script>
const tasks = [
{ id: 101, title: "读取数据", done: true },
{ id: 102, title: "创建节点", done: true },
{ id: 103, title: "插入列表", done: false }
];
const list = document.querySelector("#task-list");
const fragment = document.createDocumentFragment();
for (const task of tasks) {
const item = document.createElement("li");
item.dataset.id = String(task.id);
// 属性状态写入 DOM 属性,文本内容使用 textContent。
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = task.done;
checkbox.disabled = true;
const label = document.createElement("span");
label.textContent = task.title;
item.append(checkbox, label);
fragment.append(item);
}
// 一次替换真实容器,片段中的节点会被移动而不是复制。
list.replaceChildren(fragment);
const result = [...list.children].map((item) => ({
id: Number(item.dataset.id),
title: item.querySelector("span").textContent,
done: item.querySelector("input").checked
}));
console.log(JSON.stringify(result, null, 2));
console.log("fragmentChildren:", fragment.childNodes.length);
</script>
</body>
</html>预期结果
text
页面显示 3 条任务,前两项已勾选,第三项未勾选。
[
{
"id": 101,
"title": "读取数据",
"done": true
},
{
"id": 102,
"title": "创建节点",
"done": true
},
{
"id": 103,
"title": "插入列表",
"done": false
}
]
fragmentChildren: 0更新策略与关键边界
完整刷新适合数据量较小、列表结构简单的界面。若列表很大或只改变少数项目,直接清空并重建会丢失输入焦点、滚动位置以及节点上的临时状态,此时应根据稳定 id 查找并更新已有节点。
不要用数组索引充当长期身份。插入、删除或排序后,索引会变化,而业务 id 通常保持稳定。把 id 写入 data-id,可以为后续事件委托、局部更新和节点定位提供可靠依据。
按自己的节奏,确认真正理解。