HTML <template> ਟੈਗ

  • ਪਿਛਲਾ ਪੰਨਾ <td>
  • ਅਗਲਾ ਪੰਨਾ <textarea>

定义和用法

<template> 标签用作容器,用于在页面加载时对用户隐藏一些 HTML 内容。

<template> 内部的内容可以在稍后使用 JavaScript 呈现。

如果您有一些希望重复使用的 HTML 代码,但在需要时才显示出来,您可以使用 <template> 标签。 <template> 标签,您需要使用 JavaScript 创建 HTML 代码来防止浏览器呈现该代码。

实例

例子 1

使用 <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>

ਆਪਣੇ ਆਪ ਵਿੱਚ ਪ੍ਰਯੋਗ ਕਰੋ

例子 2

为数组中的每一项使用一个新的 div 元素填充网页。每个 div 元素的 HTML 代码都在 template 元素中:

<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>

ਆਪਣੇ ਆਪ ਵਿੱਚ ਪ੍ਰਯੋਗ ਕਰੋ

ਉਦਾਹਰਣ 3

ਬਰਾਉਜ਼ਰ ਦੇ ਸਮਰਥਨ ਦੀ ਤਸਦੀਕ ਕਰੋ <template> ਦੀ ਸਮਰਥਨ:

<script>
if (document.createElement("template").content) {
  document.write("Your browser supports template!");
} else {
  document.write("Your browser does not supports template!");
}
</script>

ਆਪਣੇ ਆਪ ਵਿੱਚ ਪ੍ਰਯੋਗ ਕਰੋ

ਸਾਰਵਤਰਿਕ ਗੁਣ

<template> ਟੈਗ ਵੀ ਸਮਰਥਨ ਕਰਦੇ ਹਨ HTML ਵਿੱਚ ਸਾਰਵਤਰਿਕ ਗੁਣ

ਬਰਾਉਜ਼ਰ ਸਮਰਥਨ

ਸਾਰੇ ਨੰਬਰ ਵਿੱਚ ਪਹਿਲੀ ਵਾਰ ਇਸ ਗੁਣ ਦਾ ਪੂਰਣ ਸਮਰਥਨ ਕਰਨ ਵਾਲੇ ਬਰਾਉਜ਼ਰ ਦੀ ਸੰਸਕਰਣ ਸੂਚੀਬੱਧ ਹੈ。

ਚਰਮੋਨੀ ਐਜ਼ ਫਾਇਰਫਾਕਸ ਸਫਾਰੀ ਓਪਰਾ
ਚਰਮੋਨੀ ਐਜ਼ ਫਾਇਰਫਾਕਸ ਸਫਾਰੀ ਓਪਰਾ
26.0 13.0 22.0 8.0 15.0
  • ਪਿਛਲਾ ਪੰਨਾ <td>
  • ਅਗਲਾ ਪੰਨਾ <textarea>