handlebars-----each循環嵌套中使用索引

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <META http-equiv=Content-Type content="text/html; charset=utf-8">
 5     <title>關於循環中索引的使用</title>
 6   </head>
 7   <body>
 8     <h1>關於循環中索引的使用</h1>
 9     <!--基礎html框架-->
10     <table>
11       <thead>
12         <tr>
13           <th>序號</th>
14           <th>姓名</th>
15           <th>性別</th>
16           <th>年齡</th>
17         </tr>
18       </thead>
19       <tbody id="tableList">
20         
21       </tbody>
22     </table>
23     
24     <!--插件引用-->
25     <script type="text/javascript" src="script/jquery.js"></script>
26     <!--注意!這個例子用的是新版本handlebars,舊版本不支持-->
27     <script type="text/javascript" src="script/handlebars-v1.3.0.js"></script>
28     
29     <!--Handlebars.js模版-->
30     <!--Handlebars.js模版放在script標籤中,保留了html原有層次結構,模版中要寫一些操作語句-->
31     <!--id可以用來唯一確定一個模版,type是模版固定的寫法-->
32     <script id="table-template" type="text/x-handlebars-template">
33       {{#each student}}
34       <tr>
35         <td>{{addOne @index}}</td>
36         <td>{{name}}</td>
37         <td>{{sex}}</td>
38         <td>{{age}}</td>
39       </tr>
40       {{/each}}
41     </script>
42     
43     <!--進行數據處理、html構造-->
44     <script type="text/javascript">
45       $(document).ready(function() {
46         //模擬的json對象
47          var data = {
48                       "student": [
49                           {
50                               "name": "張三",
51                               "sex": "0",
52                               "age": 18
53                           },
54                           {
55                               "name": "李四",
56                               "sex": "0",
57                               "age": 22
58                           },
59                           {
60                               "name": "妞妞",
61                               "sex": "1",
62                               "age": 19
63                           }
64                       ]
65                   };
66         
67         //註冊一個Handlebars模版,通過id找到某一個模版,獲取模版的html框架
68         //$("#table-template").html()是jquery的語法,不懂的童鞋請惡補。。。
69         var myTemplate = Handlebars.compile($("#table-template").html());
70         
71         //註冊一個Handlebars Helper,用來將索引+1,因爲默認是從0開始的
72         Handlebars.registerHelper("addOne",function(index,options){
73           return parseInt(index)+1;
74         });
75         
76         //將json對象用剛剛註冊的Handlebars模版封裝,得到最終的html,插入到基礎table中。
77         $('#tableList').html(myTemplate(data));
78       });
79     </script>
80   </body>

81 </html>

注:要使用新版本handlebars.js

循環過程中,當前循環的索引,一般從0開始,Handlebars.js中也是如此。

     在Handlebars.js中,可以通過{{@index}}來獲取當前的索引,也就是說@index這個變量就代表了當前索引。

     table的序號從0開始不太好,於是註冊了一個Helper,將索引+1。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章