<!DOCTYPE html>
2 <html>
3 <head>
4 <META http-equiv=Content-Type content="text/html; charset=utf-8">
5 <title>with-终极this应用 - by 杨元
</title>
6 </head>
7 <body>
8 <h1>with-终极this应用
</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 <script type="text/javascript" src="script/handlebars-1.0.0.beta.6.js"></script>
27
28 <!--Handlebars.js模版-->
29 <!--Handlebars.js模版放在script标签中,保留了html原有层次结构,模版中要写一些操作语句-->
30 <!--id可以用来唯一确定一个模版,type是模版固定的写法-->
31 <script id="table-template" type="text/x-handlebars-template">
32 {{#each this}}
33 <tr>
34 <td>{{name}}</td>
35 <td>{{sex}}</td>
36 <td>{{age}}</td>
37 <td>
38 {{#with favorite}}
39 {{#each this}}
40 <p>{{this}}</p>
41 {{/each}}
42 {{/with}}
43 </td>
44 </tr>
45 {{/each}}
46 </script>
47
48 <!--进行数据处理、html构造-->
49 <script type="text/javascript">
50 $(document).ready(function() {
51 //模拟的json对象
52 var data = [
53 {
54 "name": "张三",
55 "sex": "0",
56 "age": 18,
57 "favorite":
58 [
59 "唱歌",
60 "篮球"
61 ]
62 },
63 {
64 "name": "李四",
65 "sex": "0",
66 "age": 22,
67 "favorite":
68 [
69 "上网",
70 "足球"
71 ]
72 },
73 {
74 "name": "妞妞",
75 "sex": "1",
76 "age": 18,
77 "favorite":
78 [
79 "电影",
80 "旅游"
81 ]
82 }
83 ];
84
85 //注册一个Handlebars模版,通过id找到某一个模版,获取模版的html框架
86 //$("#table-template").html()是jquery的语法,不懂的童鞋请恶补。。。
87 var myTemplate = Handlebars.compile($("#table-template").html());
88
89 //将json对象用刚刚注册的Handlebars模版封装,得到最终的html,插入到基础table中。
90 $('#tableList').html(myTemplate(data));
91 });
92 </script>
93 </body>
94 </html>
本例和上例不同之处在于favorite属性中不再是map项,而是普通字符串,因此对于每个项,可以直接用{{this}}读取,this代表当前字符串。
所以说,this非常灵活,读者一定要大胆发挥想象力。
作者:杨元 欢迎任何形式的转载,但请务必注明出处。
转载请注明原文地址: https://ju.6miu.com/read-663753.html