HTML 5标准中最新引入的template标签介绍

现在,W3C没闲着,2013年5月,新的标准中,又引入了新的标签template模板,具体
标准见:https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html#template-element
下面综合进行小结下,供各位学习

首先,服务端的模板是不少了,大家也用的不少,现在其实就是客户端的模板,先看例子:



function supportsTemplate() {
return 'content' in document.createElement('template');
}

if (supportsTemplate()) {
//支持标签
} else {

//不支持

上面代码是监测浏览器是否支持这标签了。目前只有chrome 26以上才支持这个标签;


<template id="hhhhold-template">
<img src="" alt="random hhhhold image">
<h3 class="title"></h3>
</template>

<script>
var template = document.querySelector('#hhhhold-template');
template.content.querySelector('img').src = 'http://hhhhold.com/350x200';
template.content.querySelector('.title').textContent = 'Random image from hhhhold.com'
document.body.appendChild(template.content.cloneNode(true));
</script>


template标签中,给出了模板id,其中这里定义了空的图片,因为这些都是在
运行时动态指定的,
例子中的<SCRIPT>部门,就是通过template.content.querySelector去动态指定
填充模板的内容,记得最后要用:
document.body.appendChild(template.content.cloneNode(true));才算激活模板;

<template>标签可以放置在<head>,<body>或者<frameset>当中,也可以放在象table,tr等标签中,比如


<table>
<tr>
<template id="cells-to-repeat">
<td>some content</td>
</template>
</tr>
</table>


但模板暂时还不支持嵌套。
再来个复杂点的例子:


<button onclick="useIt()">Use me</button>
<div id="container"></div>
<script>
function useIt() {
var content = document.querySelector('template').content;

var span = content.querySelector('span');
span.textContent = parseInt(span.textContent) + 1;
document.querySelector('#container').appendChild(
content.cloneNode(true));
}
</script>

<template>
<div>Template used: <span>0</span></div>
<script>alert('Thanks!')</script>
</template>

点按钮,就会每次在模板中,不断显示template used:数字 (数字不断+1),
例子其实也很容易理解。

更详细的介绍可以参考:
http://www.html5rocks.com/en/tutorials/webcomponents/template/?redirect_from_locale=zh
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值