我试图执行这段代码,但得到的结果是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/

10-12 00:19
查看更多