A-Frame appendChild 在 Firefox 中有效,但在 Chrome 中无效

A-Frame appendChild works in Firefox but not Chrome

我正在尝试使用模板元素在 A-Frame 中动态创建新实体。辅助函数如下所示:

function htmlToElement(html) {
    const template = document.createElement('template');

    // Never return a text node of whitespace as the result.
    html = html.trim();

    template.innerHTML = html;
    return template.content.firstChild;
}

我是这样使用它的:

document.querySelector('a-scene').addEventListener('loaded', () => {
  const cube = htmlToElement('<a-box position="0 1 -2"></a-box>')

  document.querySelector('a-scene').appendChild(cube);
});

这在 Firefox 中效果很好,但在 Chrome 中实体不会显示。如果用 document.querySelector('a-box') 之类的东西查看实体,则没有 object3D 属性,所以我不认为将元素附加到场景是在 [= 上使用 A-Frame 注册元素24=]。我缺少什么才能让它在 Chrome 中工作?这是 pen.

谢谢!

innerHTML 的模板行为可能有所不同。您可以使用 createContextualFragment。要为 A 帧转储原始 HTML,请执行:

el.appendChild(document.createRange().createContextualFragment(str));

或许您可以尝试使用 insertAdjacentHTML?那时您可能不需要模板包装器。