4

I wanted to use the HTML 5 template tag but there's some confusing behaviour after a page refresh. Maybe I show you some code first:

<!doctype html>
<meta charset=utf-8>
<title>HTML 5 - template test</title>

<template>
    <h1>This is an awesome new HTML 5 template</h1>
    <p>.. some even more awesome content .. some even more awesome content .. some even more awesome content .. some even more awesome content .. some even more awesome content</p>
</template>
<div></div>

<script>
var template = document.querySelector('template'),
    templateContent = template.content.cloneNode(true);

console.log(template);
console.log(templateContent);

document.querySelector('div').appendChild(templateContent);
</script>

Actually this works as expected, but there's some confusing stuff going on in the console. When I first open the page it says:

http://i.stack.imgur.com/xDJBo.png

but when I refresh the page it shows up this:

http://i.stack.imgur.com/W23YF.png

When I repeat it I see the stuff from the first picture again. I tried it also on jsbin and there I can't see this behaviour: http://jsbin.com/ofotah/1

I have really no idea what is going on there. I'm using Google Chrome Version 27.0.1453.110 (Windows). Hope you can help me with this.

4

1 回答 1

1

这不是真正的模板相关,它是一个时髦的 Chrome 怪癖,有时会表现出来。在几乎不可能复制的条件下,它会对其他元素标签执行相同的操作,但实际对象内容永远不会受到影响。它只是有时抓取 toString() 序列化,有时抓取对象序列化。

然而,正如 Andbdrew 指出的那样,模板标签仍然是一个草稿元素,我们还没有决定它应该如何正确地成为用户或如何访问它们,所以考虑到您的示例代码如何使用它,我建议只是使用一个<script type="text/template">...</script>元素,并选择它document.querySelector("script[type='text/template']");而不是使用一个实验元素=)

于 2013-06-07T20:13:25.340 回答