首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

template

HTML<template> 元素 是一种用于保存客户端内容的机制,该内容在页面加载时不被渲染,但可以在运行时使用JavaScript进行实例化。

可以将一个模板视为正在被存储以供随后在文档中使用的一个内容片段。

虽然, 在加载页面的同时,解析器确实处理 <template>元素的内容,这样做只是确保这些内容是有效的; 然而,元素的内容不会被渲染。

内容类别

Metadata content, flow content, phrasing content, script-supporting element

允许的内容

无限制

标记遗漏

没有,起始和结束标签都是强制性的。

允许的父母

没有span属性的<body>,<frameset>,<head>,<dl>和<colgroup>

允许ARIA角色

没有

DOM接口

HTMLTemplateElement

属性

这个元素只包含全局属性。

例子

首先我们从示例的HTML部分开始。

代码语言:javascript
复制
<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片段的结构。

既然已经创建了表格并定义了模板,我们使用JavaScript将行插入到表格中,每一行都是以模板为基础构建的。

代码语言: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

扫码关注腾讯云开发者

领取腾讯云代金券