HTML <แม่แบบ>แท็ก
ตัวอย่าง
ใช้ <template> เพื่อเก็บเนื้อหาบางส่วนที่จะซ่อนเมื่อโหลดหน้า ใช้ JavaScript เพื่อแสดง:
<button onclick="showContent()">Show hidden content</button>
<template>
<h2>Flower</h2>
<img src="img_white_flower.jpg" width="214"
height="204">
</template>
<script>
function showContent() {
var temp =
document.getElementsByTagName("template")[0];
var clon =
temp.content.cloneNode(true);
document.body.appendChild(clon);
}
</script>
ตัวอย่าง "ลองใช้เอง" เพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
แท็ ก<template>
นี้ใช้เป็นคอนเทนเนอร์เพื่อเก็บเนื้อหา HTML บางส่วนที่ซ่อนจากผู้ใช้เมื่อโหลดหน้าเว็บ
เนื้อหาภายใน<template>
สามารถแสดงผลได้ในภายหลังด้วย JavaScript
คุณสามารถใช้<template>
แท็กได้หากคุณมีโค้ด HTML บางส่วนที่ต้องการใช้ซ้ำแล้วซ้ำอีก แต่ไม่ใช่จนกว่าคุณจะขอ ในการทำเช่นนี้โดยไม่มี แท็ ก<template>
คุณต้องสร้างโค้ด HTML ด้วย JavaScript เพื่อป้องกันไม่ให้เบราว์เซอร์แสดงโค้ด
รองรับเบราว์เซอร์
Element | |||||
---|---|---|---|---|---|
<template> | 26.0 | 13.0 | 22.0 | 8.0 | 15.0 |
คุณสมบัติสากล
แท็ ก<template>
รองรับGlobal Attributes ใน HTML
ตัวอย่างเพิ่มเติม
ตัวอย่าง
เติมหน้าเว็บด้วยองค์ประกอบ div ใหม่สำหรับแต่ละรายการในอาร์เรย์ โค้ด HTML ขององค์ประกอบ div แต่ละองค์ประกอบอยู่ภายในองค์ประกอบเทมเพลต:
<template>
<div class="myClass">I like: </div>
</template>
<script>
var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar",
"Nissan"];
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>
ตัวอย่าง
ตรวจสอบการรองรับเบราว์เซอร์สำหรับ <แม่แบบ>:
<script>
if (document.createElement("template").content) {
document.write("Your browser supports template!");
} else {
document.write("Your browser does not supports template!");
}
</script>