gpt4 book ai didi

javascript - 为什么 DocumentFragment 会忽略一些附加节点?

转载 作者:行者123 更新时间:2023-11-28 00:46:43 24 4
gpt4 key购买 nike

我正在尝试执行这段代码,但得到的结果是 first third , 完全忽略中间 <b>second</b>节点。谁能告诉我问题出在哪里?

const html = 'first <b>second</b> third ';
const span = document.createElement('span');
const frag = document.createDocumentFragment();
span.innerHTML = html;

for (let node of span.childNodes) {
frag.appendChild(node);
}

document.body.appendChild(frag);

最佳答案

这是因为您正在改变您正在遍历的节点列表。每次从 span 中删除一个节点(通过将其附加到片段),.childNodes 都会更新并重新编制索引。

由于您要传输所有节点,因此请使用 while 循环,只要至少有一个子节点就会运行,并将 .firstChild 附加到片段中。

const html = 'first <b>second</b> third ';
const span = document.createElement('span');
const frag = document.createDocumentFragment();
span.innerHTML = html;

while (span.firstChild) {
frag.appendChild(span.firstChild);
}

document.body.appendChild(frag);


或者只使用 .insertAdjacentHTML()而不是所有这些转移。

const html = 'first <b>second</b> third ';

document.body.insertAdjacentHTML("beforeend", html);

关于javascript - 为什么 DocumentFragment 会忽略一些附加节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50043426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com