我有一个<template>
有几个子元素。我通过克隆这些子元素.cloneNode(true)
并将它们附加到document.head
.
<template id="my_template">
<script>
// …
</script>
</template>
var template=document.getElementById('my_template');
document.head.appendChild(template.content.cloneNode(true));
我想要的是
有没有办法在任何给定时刻判断是否document.head
已经包含<template>
内容?
我试过的
- 维护标志例如
template.setAttribute('data-cloned', 1)
有效,但这是一种解决方法 document.head.contains()
不起作用可能是因为克隆的元素在内部是不同的:for (var i=0; i<template.content.children.length; i++) { document.head.contains(template.content.children[i]); // always false }
- 循环遍历每个模板元素与内部的每个元素
document.head
,并使用 , 比较它们.is()
,否则它们.outerHTML
似乎不是很有效。
我现在正在使用 flag 属性,但我很想知道是否有一种方法可以通过仅使用模板内容和document.head
不创建属性或 className 混乱和/或额外修改它们来完成此操作。只要可能且合理,我想避免依赖 jQuery。