?
This document uses PHP Chinese website manual Release
HTML<template>
元素 是一種用于保存客戶端內(nèi)容的機(jī)制,該內(nèi)容在頁(yè)面加載時(shí)不被渲染,但可以在運(yùn)行時(shí)使用JavaScript進(jìn)行實(shí)例化。
可以將一個(gè)模板視為正在被存儲(chǔ)以供隨后在文檔中使用的一個(gè)內(nèi)容片段。
雖然, 在加載頁(yè)面的同時(shí),解析器確實(shí)處理 <template>
元素的內(nèi)容,這樣做只是確保這些內(nèi)容是有效的; 然而,元素的內(nèi)容不會(huì)被渲染。
內(nèi)容類別 | Metadata content, flow content, phrasing content, script-supporting element |
---|---|
允許的內(nèi)容 | 無(wú)限制 |
標(biāo)記遺漏 | 沒(méi)有,起始和結(jié)束標(biāo)簽都是強(qiáng)制性的。 |
允許的父母 | 沒(méi)有span屬性的<body>,<frameset>,<head>,<dl>和<colgroup> |
允許ARIA角色 | 沒(méi)有 |
DOM接口 | HTMLTemplateElement |
這個(gè)元素只包含全局屬性。
首先我們從示例的HTML部分開(kāi)始。
<table id="producttable"> <thead> <tr> <td>UPC_Code</td> <td>Product_Name</td> </tr> </thead> <tbody> <!-- existing data could optionally be included here --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template>
首先,我們有一個(gè)表格,稍后我們將使用JavaScript代碼插入內(nèi)容。然后是模板,它描述了表示單個(gè)表格行的HTML片段的結(jié)構(gòu)。
既然已經(jīng)創(chuàng)建了表格并定義了模板,我們使用JavaScript將行插入到表格中,每一行都是以模板為基礎(chǔ)構(gòu)建的。
// Test to see if the browser supports the HTML template element by checking // for the presence of the template element's content attribute. if ('content' in document.createElement('template')) { // Instantiate the table with the existing HTML tbody // and the row with the template var t = document.querySelector('#productrow'), td = t.content.querySelectorAll("td"); td[0].textContent = "1235646565"; td[1].textContent = "Stuff"; // Clone the new row and insert it into the table var tb = document.querySelector("tbody"); var clone = document.importNode(t.content, true); tb.appendChild(clone); // Create a new row td[0].textContent = "0384928528"; td[1].textContent = "Acme Kidney Beans"; // Clone the new row and insert it into the table var clone2 = document.importNode(t.content, true); tb.appendChild(clone2);} else { // Find another way to add the rows to the table because // the HTML template element is not supported. }
結(jié)果是原始的HTML表格,通過(guò)JavaScript附加了兩個(gè)新的行:
Specification | Status | Comment |
---|---|---|
HTML Living StandardThe definition of 'template element' in that specification. | Living Standard | |
HTML5The definition of 'template element' in that specification. | Recommendation | Initial definition |
Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic Support | 26 | 13 | 22 | No | 15 | 7.1 |
Feature | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
---|---|---|---|---|---|---|---|
Basic Support | ? | ? | (Yes) | 22 | No | ? | 8 |