使用jQuery+huandlebars循环中索引(@index)使用技巧(访问父级索引)
兼容ie8(很实用,复制过来,仅供技术参考,更详细内容请看源地址:http://www.cnblogs.com/iyangyuan/archive/2013/12/12/3471227.html)
<!DOCTYPE html> <html> <head> <META http-equiv=Content-Type content="text/html; charset=utf-8"> <title>Handlebars.js循环中索引(@index)使用技巧 - by 杨元</title> </head> <body> <h1>Handlebars.js循环中索引(@index)使用技巧</h1> <!--基础html框架--> <table> <thead> <tr> <th></th> <th>姓名</th> <th>性别</th> <th>年龄</th> </tr> </thead> <tbody id="tableList"> </tbody> </table> <!--插件引用--> <script type="text/javascript" src="script/jquery.js"></script> <script type="text/javascript" src="script/handlebars-v1.3.0.js"></script> <!--Handlebars.js模版--> <!--Handlebars.js模版放在script标签中,保留了html原有层次结构,模版中要写一些操作语句--> <!--id可以用来唯一确定一个模版,type是模版固定的写法--> <script id="table-template" type="text/x-handlebars-template"> {{#each this}} <tr> <td>{{addOne @index}}</td> <td>{{name}}</td> <td>{{sex}}</td> <td>{{age}}</td> </tr> {{#each family}} <tr> <td>{{../_index}}.{{@index}}</td> <td>{{name}}</td> <td>{{sex}}</td> <td>{{age}}</td> </tr> {{/each}} {{/each}} </script> <!--进行数据处理、html构造--> <script type="text/javascript"> var data = [{ name: "张三", sex: "男", age: 35, family: [{ name: "张三儿子", sex: "男", age: 10, },{ name: "张三妻子", sex: "女", age: 33, }] },{ name: "李四", sex: "男", age: 23, family: [{ name: "李四妻子", sex: "女", age: 23, }] },{ name: "甜妞", sex: "女", age: 18, family: [{ name: "甜妞妈妈", sex: "女", age: 40, },{ name: "甜妞爸爸", sex: "男", age: 43, },{ name: "甜妞姥爷", sex: "男", age: 73, }] }]; //注册索引+1的helper var handleHelper = Handlebars.registerHelper("addOne",function(index){ //利用+1的时机,在父级循环对象中添加一个_index属性,用来保存父级每次循环的索引 this._index = index+1; //返回+1之后的结果 return this._index; }); //解析模版 var handle = Handlebars.compile($("#table-template").html()); //生成html var html = handle(data); //插入到页面 $("#tableList").append(html); </script> </body> </html>
posted on 2017-08-24 16:20 lengyue0030 阅读(276) 评论(0) 编辑 收藏 举报