現在,W3C沒閑着,2013年5月,新的標准中,又引入了新的標簽template模板,具體
標准見:https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html#template-element
下面綜合進行小結下,供各位學習
首先,服務端的模板是不少了,大家也用的不少,現在其實就是客戶端的模板,先看例子:
[code="java"]
1 function supportsTemplate() { 2 return 'content' in document.createElement('template'); 3 } 4 5 if (supportsTemplate()) { 6 //支持標簽 7 } else {}
//不支持
[/code]
上面代碼是監測瀏覽器是否支持這標簽了。目前只有chrome 26以上才支持這個標簽;
[code="java"]
<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>
[/code]
template標簽中,給出了模板id,其中這里定義了空的圖片,因為這些都是在
運行時動態指定的,
例子中的<SCRIPT>部門,就是通過template.content.querySelector去動態指定
填充模板的內容,記得最后要用:
document.body.appendChild(template.content.cloneNode(true));才算激活模板;
<template>標簽可以放置在<head>,<body>或者<frameset>當中,也可以放在象table,tr等標簽中,比如
[code="java"]
1 <table> 2 <tr> 3 <template id="cells-to-repeat"> 4 <td>some content</td> 5 </template> 6 </tr> 7 </table>
[/code]
但模板暫時還不支持嵌套。
再來個復雜點的例子:
[code="java"]
1 <button onclick="useIt()">Use me</button> 2 <div id="container"></div> 3 <script> 4 function useIt() { 5 var content = document.querySelector('template').content; 6 7 var span = content.querySelector('span'); 8 span.textContent = parseInt(span.textContent) + 1; 9 document.querySelector('#container').appendChild( 10 content.cloneNode(true)); 11 } 12 </script>
1 <template> 2 <div>Template used: <span>0</span></div> 3 <script>alert('Thanks!')</script> 4 </template>
[/code]
點按鈕,就會每次在模板中,不斷顯示template used:數字 (數字不斷+1),
例子其實也很容易理解。
轉載:https://my.oschina.net/jackyrong/blog/132763
更詳細的介紹可以參考:
http://www.html5rocks.com/en/tutorials/webcomponents/template/?redirect_from_locale=zh