?
本文檔使用 php中文網手冊 發(fā)布
HTML<template>
元素 是一種用于保存客戶端內容的機制,該內容在頁面加載時不被渲染,但可以在運行時使用JavaScript進行實例化。
可以將一個模板視為正在被存儲以供隨后在文檔中使用的一個內容片段。
雖然, 在加載頁面的同時,解析器確實處理 <template>
元素的內容,這樣做只是確保這些內容是有效的; 然而,元素的內容不會被渲染。
內容類別 | Metadata content, flow content, phrasing content, script-supporting element |
---|---|
允許的內容 | 無限制 |
標記遺漏 | 沒有,起始和結束標簽都是強制性的。 |
允許的父母 | 沒有span屬性的<body>,<frameset>,<head>,<dl>和<colgroup> |
允許ARIA角色 | 沒有 |
DOM接口 | HTMLTemplateElement |
這個元素只包含全局屬性。
首先我們從示例的HTML部分開始。
<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>
首先,我們有一個表格,稍后我們將使用JavaScript代碼插入內容。然后是模板,它描述了表示單個表格行的HTML片段的結構。
既然已經創(chuàng)建了表格并定義了模板,我們使用JavaScript將行插入到表格中,每一行都是以模板為基礎構建的。
// 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. }
結果是原始的HTML表格,通過JavaScript附加了兩個新的行:
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 |