HTML 5模板标记(页面刷新)

时间:2013-06-07 17:54:27

标签: javascript html5 html5-template

我想使用HTML 5模板标记,但页面刷新后会出现一些令人困惑的行为。也许我先给你看一些代码:

<!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>

实际上这可以按预期工作,但在控制台中有一些令人困惑的事情。当我第一次打开页面时,它说:

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

但是当我刷新页面时,它会显示出来:

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

当我重复它时,我再次看到第一张照片中的东西。 我也在jsbin上试过它,在那里我看不到这种行为: http://jsbin.com/ofotah/1

我真的不知道那里发生了什么。我正在使用 Google Chrome版本27.0.1453.110(Windows)。 希望你能帮助我。

1 个答案:

答案 0 :(得分:1)

这与模板无关,它是一种时髦的Chrome怪癖,有时会出现。在几乎不可能再现的条件下,它对其他元素标签也会这样做,但实际的对象内容永远不会受到影响。它有时会抓取toString()序列化,有时会抓取对象序列化。

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

相关问题