模版的幾種表示方式
- 模版元素忧陪,HTML5 中的新玩意兒,template :
<template id="template">
<p>This is a template</p>
</template>
在支持 template 標簽的瀏覽器中是看不到任何信息的阵翎,不支持此標簽的會顯示: This is a template
- 在 template 標簽誕生之前一般都是利用 script 標簽來實現(xiàn)模版功能的:
<script type="text/template" id="template">
<p>This is the second type template</p>
</script>
這是利用了 script 標簽中的內(nèi)容天生不顯示的特性來達到目的的,另外,text/template 這個 type 是不存在的,只是為了凸顯其作用,而另行與標準之外的設(shè)定。
- 模版桶唐,模版,見名知意茉兰,網(wǎng)頁中的模版尤泽,就是不需要顯示出來,只要為需要顯示的頁面部分做出規(guī)范规脸。
可以看出主要就是不需要其顯示坯约,而又能取出需要的內(nèi)容:
<div style="display:none" id="template">
<p>This is the third type template</p>
</div>
innerHTML、outerHTML
簡述其區(qū)別就是:
innerHTML:從對象起始位置到終止位置的全部內(nèi)容莫鸭,不包括 html 標簽闹丐。
outerHTML:除了包含 innerHTML 的全部內(nèi)容外,還包含 html 標簽本身被因。
<div id="div">This is a div</div>
// 'This is a div'
console.log(div.innerHTML);
// '<div id="div">This is a div</div>'
console.log(div.outerHTML);
取出模版元素
// template tag
template.content
// script
template.innerHTML
// hidden tag
template.outerHTML
template-parser
當然卿拴,解析模版是少不了 fragment 的幫忙的衫仑。
var toFragment = require('./fragment');
/**
* 將模版解析為文檔碎片
* 可以傳入如下幾種模式的參數(shù):
* id 選擇器: '#some-template-id'
* 模版字符串: '<div><span>my template</span></div>'
* DocumentFragment 對象
* 模版節(jié)點
*/
module.exports = function(template) {
var templateNode;
// 如果是 DocumentFragment 對象,直接返回
if(template instanceof window.DocumentFragment) {
return template;
}
if(typeof template === 'string') {
// '#' 開頭的字符串當作 id 選擇器處理
if(template.charAt(0) === '#') {
templateNode = document.getElementById(template.slice(1));
if(!templateNode) return;
// 不是 '#' 開頭的堕花,作為模版字符串文狱,直接處理
} else {
return toFragment(template);
}
// 模版節(jié)點,后續(xù)繼續(xù)處理
} else if(template.nodeType) {
templateNode = template;
} else {
return;
}
// 瀏覽器支持 template 標簽航徙,其 content 已經(jīng)是一個文檔碎片
if(templateNode.tagName === 'TEMPLATE' && templateNode.content) {
return templateNode.content;
}
// script 標簽中的內(nèi)容會被當作字符串處理
if(templateNode.tagName === 'SCRIPT') {
return toFragment(templateNode.innerHTML);
}
// 普通節(jié)點如贷,連同其標簽本身一起作為字符串去處理
return toFragment(templateNode.outerHTML);
}