您的位置:首页 > Web前端 > JQuery

jQuery: 做一个简单的模版加载

2016-01-09 14:27 549 查看
直接上,简单明了的一小段代码:

[code]<head>
    <!-- 依赖:jQuery, underscore -->
    <script src="//cdn.bootcss.com/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="//cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.js"></script>
</head>

<body>
<!-- 业务部分 HTML -->
<table id="sample"></table>

<!-- 脚本 -->
<script>
// 加载模版
$(function() {
  var tpls = $.tpls = {};
  $('[type=x-html-template]').each(function(ind, tpl) {
    tpls[tpl.id] = _.template(tpl.innerHTML);
    $(tpl).remove();
  });
});

// 业务逻辑
$(function() {
    var users = [
        {firstName: 'Alex', lastName: 'Enderby'},
        {firstName: 'Bill', lastName: 'Smith'}
    ];
    // 使用模版
    _.each(users, function(user) {
        var tpl = $.tpls['tpl-row'];
        $('#sample').append(tpl(user));
    });

});
</script>

<!-- 多多的弄几个模版,通过 $.tpls[NAME] 的方式获取对象 -->
<script type="x-html-template" id="tpl-row">
  <tr>
    <td><%= firstName %></td>
    <td><%= lastName %></td>
  </tr>
</script>

</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: