HTML <template> 标签
定义和用法
<template> 标记将其内容隐藏在客户端之外.
<template> 标记内的内容不会呈现.
通过使用JavaScript,内容可以在以后显示和呈现.
如果您想要反复使用HTML代码,请使用 <template> 标记,但直到您要求它为止.要在没有 <template> 标记的情况下执行此操作,您必须使用JavaScript创建HTML代码以防止浏览器呈现代码.
浏览器支持
Element | |||||
---|---|---|---|---|---|
<template> | 26.0 | 13.0 | 22.0 | 9 | 15.0 |
HTML 4.01和HTML5之间的差异
<template> 标记是HTML5中的新标记.
全局属性
<template> 标记支持HTML中的 全局属性 .
更多例子
实例
使用JavaScript从模板中获取内容,并将其添加到页面中:
function showContent() {
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
运行 »
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
实例
使用模板的内容为数组中的每个项目:
<template>
<div class="myClass">I like: </div>
</template>
<script>
var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
function showContent() {
var temp, item, a, i;
//get the template element:
temp = document.getElementsByTagName("template")[0];
//get the DIV element from the template:
item = temp.content.querySelector("div");
//for each item in the array:
for (i = 0; i < myArr.length; i++) {
//Create a new node, based on the template:
a = document.importNode(item, true);
//Add data from the array:
a.textContent += myArr[i];
//append the new node wherever you like:
document.body.appendChild(a);
}
}
</script>
运行 »
<div class="myClass">I like: </div>
</template>
<script>
var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
function showContent() {
var temp, item, a, i;
//get the template element:
temp = document.getElementsByTagName("template")[0];
//get the DIV element from the template:
item = temp.content.querySelector("div");
//for each item in the array:
for (i = 0; i < myArr.length; i++) {
//Create a new node, based on the template:
a = document.importNode(item, true);
//Add data from the array:
a.textContent += myArr[i];
//append the new node wherever you like:
document.body.appendChild(a);
}
}
</script>
实例
测试浏览器对模板元素的支持::
if (document.createElement("template").content) {
/*Code for browsers that supports the TEMPLATE element*/
} else {
/*Alternative code for browsers that do not support the TEMPLATE element*/
}
运行 »
/*Code for browsers that supports the TEMPLATE element*/
} else {
/*Alternative code for browsers that do not support the TEMPLATE element*/
}