我想使用 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>
实际上这按预期工作,但控制台中发生了一些令人困惑的事情。当我第一次打开页面时,它显示:
但是当我刷新页面时,它显示了这个:
当我重复它时,我又看到了第一张图片中的东西。 我也在 jsbin 上尝试过,但我看不到这种行为: http://jsbin.com/ofotah/1
我真的不知道那里发生了什么。我使用的是 Google Chrome 版本 27.0.1453.110 (Windows)。 希望你能帮我解决这个问题。
最佳答案
这实际上与模板无关,它是 Chrome 浏览器有时会出现的怪癖。在几乎不可能重现的条件下,它会对其他元素标签执行相同的操作,但实际对象内容不会受到影响。它只是有时获取 toString() 序列化,有时获取对象序列化。
然而,正如 Andbdrew 指出的那样,模板标签仍然是一个草稿元素,我们还远未决定它应该如何正确使用或如何访问它们,所以考虑到您的示例代码如何使用它,我建议只使用 <script type="text/template">...</script>
元素,并使用 document.querySelector("script[type='text/template']");
选择它而不是使用实验元素 =)
关于javascript - HTML 5 模板标签(页面刷新),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16990169/