jquery模板jquery.tmpl.js使用教程(附jquery.tmpl.js下载)

使用js tempate的意义:
用js对json数据处理生成html,如果不复杂还可以,复杂了就不好处理了,而且让js代码看起来特不优雅,维护这种代码等于自杀啊,别谈扩展性了。。。
介绍一个jquery模板 jquery.tmpl.js,使用案例如下:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title></title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
  7. <script src="jquery.tmpl.min.js" type="text/javascript"></script>
  8. <script>
  9. $(function () {
  10. var website = [{ url: 'www.phpddt.com', name: 'PHP点点通', tags: ['web教程', '博客'] }, { url: 'www.baidu.com', name: '百度', tags: ['搜索引擎', '中文搜索']}];
  11. //$('#myTemplate').tmpl(website).appendTo('#rows');
  12. $('#myTemplate').tmpl(website, {
  13. getTags: function (separator) {
  14. return this.data.tags.join(separator);
  15. }
  16. }).appendTo('#rows');
  17. });
  18. </script>
  19. <script id="myTemplate" type="text/x-jquery-tmpl">
  20. <tr><td>${$data.url}</td><td>${$data.name}</td><td>${$item.getTags(';')}</td></tr>
  21. </script>
  22. </head>
  23. <body>
  24. <table cellspacing="0" cellpadding="3" border="1">
  25. <tbody id="rows">
  26. </tbody>
  27. </table>
  28. </body>
  29. </html>


常见的一些方法:
$.template()方法,
将一段Html编译为模板。
${}:占位符,另一种写法{{= field}},必须注意的是"="号后必须跟一个空格。

$item$data两个属性:$item代表当前的模板;$data代表当前的数据。
 {{each}}循环
{{if}}和{{else}}逻辑判断
{{html}},直接将对象属性值作为HTML代码替换占位符
{{wrap}},包装器,这回不需要指定对哪一个元素使用模板了,直接生成模板的包装器 
$.tmplItem()方法,使用这个方法,可以获取从render出来的元素上重新获取$item 

你可能感兴趣的:(jquery模板jquery.tmpl.js使用教程(附jquery.tmpl.js下载))