<!DOCTYPE html>
<html>
<body>
<style>
.myClass {
color: white;
background-color: DodgerBlue;
padding: 20px;
text-align: center;
margin: 10px;
}
</style>
<h1>template 元素</h1>
<p>本例使用包含数组中每个项目的新 div 元素来填充网页。</p>
<p>每个 div 的 HTML 代码在 template 元素内。</p>
<p>单击下面的按钮,显示 template 元素中的隐藏内容。</p>
<button onclick="showContent()">显示隐藏的内容</button>
<template>
<div class="myClass">我喜欢:</div>
</template>
<script>
var myArr = ["奥迪", "宝马", "奔驰", "大众", "捷豹", "沃尔沃"];
function showContent() {
var temp, item, a, i;
temp = document.getElementsByTagName("template")[0];
item = temp.content.querySelector("div");
for (i = 0; i < myArr.length; i++) {
a = document.importNode(item, true);
a.textContent += myArr[i];
document.body.appendChild(a);
}
}
</script>
</body>
</html>