我需要在使用 <template>
之间做出决定或者只是使用 documentFragment
在 Javascript 中构造一个高度嵌套的元素.使用 <template>
会干净很多,但 Edge 支持很关键,caniuse.com
似乎表明不支持版本 12,仅部分支持版本 13-14:
https://caniuse.com/#feat=template
Does not support Document.importNode on templates, nested templates or elements that contain templates.
Does not support Node.cloneNode on templates, nested templates or elements that contain templates.
问题是我无法使用 Edge 进行测试(未运行 Windows 10,也无法访问浏览器测试套件),而且我也无法在 MDN 或 Microsoft 文档中找到任何关于它的在线信息.无法将模板克隆到文档中几乎意味着使用 <template>
的标准方式走出窗外,这对我来说没有意义,因为这似乎是 <template>
的重点.
唯一声称这是 caniuse.com
的地方但我已经学会了相信它,这让我不确定要使用哪种方法。我可能会使用 documentFragment
为了安全起见,但我想知道这是否是 caniuse.com
上的错误或者如果有另一种合理的使用方式 <template>
这很明显,我想念它。
最佳答案
以下测试文档演示了 importNode
和 cloneNode
似乎与 Edge 中的 template
一起正常工作,至少对于版本 15 及更高版本。
<!DOCTYPE html>
<title><template> testing</title>
<div id="wrapper">
<template id="outer">lol<template id="inner">wut</template></template>
</div>
<script>
var wrapper = document.getElementById('wrapper').cloneNode(true);
var outer = wrapper.querySelector('#outer');
var clone = outer.cloneNode(true);
var inner = document.importNode(clone.content.lastChild, true);
var content = document.importNode(inner.content, true);
document.body.appendChild(content);
</script>
就其值(value)而言,您通常不会像问题中提到的那样“将模板克隆到文档中”,而是将模板的内容克隆到文档中:
let template = document.querySelector('template');
document.body.append(document.importNode(template.content, true));
关于javascript - Edge 上的 HTML <template>(版本 ≥13),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48400009/