handlebars-----each循環使用方法

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <META http-equiv=Content-Type content="text/html; charset=utf-8">
 5     <title>each-基本循環使用方法 - by 楊元</title>
 6   </head>
 7   <body>
 8     <h1>each-基本循環使用方法</h1>
 9     <!--基礎html框架-->
10     <table>
11       <thead>
12         <tr>
13           <th>姓名</th>
14           <th>性別</th>
15           <th>年齡</th>
16         </tr>
17       </thead>
18       <tbody id="tableList">
19         
20       </tbody>
21     </table>
22     
23     <!--插件引用-->
24     <script type="text/javascript" src="script/jquery.js"></script>
25     <script type="text/javascript" src="script/handlebars-1.0.0.beta.6.js"></script>
26     
27     <!--Handlebars.js模版-->
28     <!--Handlebars.js模版放在script標籤中,保留了html原有層次結構,模版中要寫一些操作語句-->
29     <!--id可以用來唯一確定一個模版,type是模版固定的寫法-->
30     <script id="table-template" type="text/x-handlebars-template">
31       {{#each student}}
32         <tr>
33           <td>{{name}}</td>
34           <td>{{sex}}</td>
35           <td>{{age}}</td>
36         </tr> 
37       {{/each}}
38     </script>
39     
40     <!--進行數據處理、html構造-->
41     <script type="text/javascript">
42       $(document).ready(function() {
43         //模擬的json對象
44         var data = {
45                     "student": [
46                         {
47                             "name": "張三",
48                             "sex": "0",
49                             "age": 18
50                         },
51                         {
52                             "name": "李四",
53                             "sex": "0",
54                             "age": 22
55                         },
56                         {
57                             "name": "妞妞",
58                             "sex": "1",
59                             "age": 18
60                         }
61                     ]
62                 };
63         
64         //註冊一個Handlebars模版,通過id找到某一個模版,獲取模版的html框架
65         //$("#table-template").html()是jquery的語法,不懂的童鞋請惡補。。。
66         var myTemplate = Handlebars.compile($("#table-template").html());
67         
68         //將json對象用剛剛註冊的Handlebars模版封裝,得到最終的html,插入到基礎table中。
69         $('#tableList').html(myTemplate(data));
70       });
71     </script>
72   </body>
73 </html>
注:#each循環的是json對象的student屬性,json的鍵值是字符串,要使用引號包裹。很多時候,我們拿到的json對象,本身就是一個list,   並不是map,直接就可以遍歷,不需要#each student這樣指定遍歷某個屬性。 此時可以用#each this,表示遍歷當前對象。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章