js模版引擎handlebars.js实用教程——each-循环中使用this
2013-12-12 15:59
615 查看
返回目录
很多时候,我们拿到的json对象,本身就是一个list,并不是map,直接就可以遍历,不需要#each student这样指定遍历某个属性。
此时可以用#each this,表示遍历当前对象。
this表示当前上下文,非常灵活,以后还会提及,读者可以举一反三。
<!DOCTYPE html> <html> <head> <META http-equiv=Content-Type content="text/html; charset=utf-8"> <title>each-循环中使用this - by 杨元</title> </head> <body> <h1>each-循环中使用this</h1> <!--基础html框架--> <table> <thead> <tr> <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-1.0.0.beta.6.js"></script> <!--Handlebars.js模版--> <!--Handlebars.js模版放在script标签中,保留了html原有层次结构,模版中要写一些操作语句--> <!--id可以用来唯一确定一个模版,type是模版固定的写法--> <script id="table-template" type="text/x-handlebars-template"> {{#each this}} <tr> <td>{{name}}</td> <td>{{sex}}</td> <td>{{age}}</td> </tr> {{/each}} </script> <!--进行数据处理、html构造--> <script type="text/javascript"> $(document).ready(function() { //模拟的json对象 var data = [ { "name": "张三", "sex": "0", "age": 18 }, { "name": "李四", "sex": "0", "age": 22 }, { "name": "妞妞", "sex": "1", "age": 18 } ]; //注册一个Handlebars模版,通过id找到某一个模版,获取模版的html框架 //$("#table-template").html()是jquery的语法,不懂的童鞋请恶补。。。 var myTemplate = Handlebars.compile($("#table-template").html()); //将json对象用刚刚注册的Handlebars模版封装,得到最终的html,插入到基础table中。 $('#tableList').html(myTemplate(data)); }); </script> </body> </html>
很多时候,我们拿到的json对象,本身就是一个list,并不是map,直接就可以遍历,不需要#each student这样指定遍历某个属性。
此时可以用#each this,表示遍历当前对象。
this表示当前上下文,非常灵活,以后还会提及,读者可以举一反三。
相关文章推荐
- js模版引擎handlebars.js实用教程——each-基本循环使用方法
- js模版引擎handlebars.js实用教程——循环中使用索引
- js模版引擎handlebars.js实用教程——with-终极this应用
- handlebars.js模版引擎中EACH循环遍历的使用
- js模版引擎handlebars.js实用教程——目录
- js模版引擎handlebars.js实用教程——目录
- Js模版引擎handlebars.js实用教程——目录
- js模版引擎handlebars.js实用教程——if-判断的基本用法
- js模版引擎handlebars.js实用教程——目录
- js模版引擎handlebars.js实用教程——目录
- js模版引擎handlebars.js实用教程——如何引入Handlebars.js
- js模版引擎handlebars.js实用教程——由于if功力不足引出的Helper
- js模版引擎handlebars.js实用教程——由于if功力不足引出的Helper
- js模版引擎handlebars.js实用教程——if-判断的基本用法
- js模版引擎handlebars.js实用教程——为什么选择Handlebars.js
- js模版引擎handlebars.js实用教程——由于if功力不足引出的Helper
- js模版引擎handlebars.js实用教程——目录
- js模版引擎handlebars.js实用教程——each嵌套
- js模版引擎handlebars.js实用教程——关于HTML编码
- js模版引擎handlebars.js实用教程――为什么选择Handlebars.js