1 <!DOCTYPE html> 2 <html> 3 <head> 4 <META http-equiv=Content-Type content="text/html; charset=utf-8"> 5 <title>Handlebars.js循环中索引(@index)使用技巧 - by 杨元</title> 6 </head> 7 <body> 8 <h1>Handlebars.js循环中索引(@index)使用技巧</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-v1.3.0.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>{{addOne @index}}</td> 35 <td>{{name}}</td> 36 <td>{{sex}}</td> 37 <td>{{age}}</td> 38 </tr> 39 {{#each family}} 40 <tr> 41 <td>{{../_index}}.{{@index}}</td> 42 <td>{{name}}</td> 43 <td>{{sex}}</td> 44 <td>{{age}}</td> 45 </tr> 46 {{/each}} 47 {{/each}} 48 </script> 49 50 <!--进行数据处理、html构造--> 51 <script type="text/javascript"> 52 var data = [{ 53 name: "张三", 54 sex: "男", 55 age: 35, 56 family: [{ 57 name: "张三儿子", 58 sex: "男", 59 age: 10, 60 },{ 61 name: "张三妻子", 62 sex: "女", 63 age: 33, 64 }] 65 },{ 66 name: "李四", 67 sex: "男", 68 age: 23, 69 family: [{ 70 name: "李四妻子", 71 sex: "女", 72 age: 23, 73 }] 74 },{ 75 name: "甜妞", 76 sex: "女", 77 age: 18, 78 family: [{ 79 name: "甜妞妈妈", 80 sex: "女", 81 age: 40, 82 },{ 83 name: "甜妞爸爸", 84 sex: "男", 85 age: 43, 86 },{ 87 name: "甜妞姥爷", 88 sex: "男", 89 age: 73, 90 }] 91 }]; 92 93 //注册索引+1的helper 94 var handleHelper = Handlebars.registerHelper("addOne",function(index){ 95 //利用+1的时机,在父级循环对象中添加一个_index属性,用来保存父级每次循环的索引 96 this._index = index+1; 97 //返回+1之后的结果 98 return this._index; 99 }); 100 //解析模版 101 var handle = Handlebars.compile($("#table-template").html()); 102 //生成html 103 var html = handle(data); 104 //插入到页面 105 $("#tableList").append(html); 106 </script> 107 </body>108 </html>
注:可以用类似{{../name}}这种语法访问父级循环中的属性,但是这样访问父级索引是不可以的
handlebars-----each创建分级索引
最新推荐文章于 2023-09-12 23:17:38 发布