數據結構簡單的時候可使用模版引擎。實際上就是一個API。html
1)參數1:模板的idgit
2)參數2:分配的數據,必須是一個JS對象的形式github
3)一個返回值:是數據和模板標籤組合好的結果web
定義模板時的script標籤必定好指定 id 和 type數據結構
tempalte函數語法:var html = template(模板id, Object);
函數
1 <!-- 1. 定義一個模板,要指定script的id和type屬性 --> 2 <script id="moban" type="text/html"> 3 <h1>{{title}}</h1> 4 <ul> 5 <li> 6 <p>{{chenghu}}</p> 7 <p>{{liuyan}}</p> 8 </li> 9 </ul> 10 </script> 11 12 13 <script src="./assets/template-web.js"></script> 14 15 <script> 16 // 調用template函數 17 // 兩個參數,一個返回值 18 // 參數1:模板的id 19 // 參數2:要顯示的數據,必須是JS對象的形式 20 // 返回值:數據和模板拼接好的結果 21 var html = template('moban', { 22 title: '留言板123', 23 chenghu: '張三', 24 liuyan: 'hahahahahaha哈哈哈' 25 }); 26 console.log(html); 27 document.body.innerHTML = html; 28 </script>