JSON对象进入Mustache.js表 [英] JSON Object into Mustache.js Table

查看:100
本文介绍了JSON对象进入Mustache.js表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Mustache.js创建一个带有JSON对象的表。
我希望它显示两行,但它只显示第二行。
我怀疑第一行被第二行覆盖,当它再次在循环中被绑定时。

I'm trying to create a table with a JSON Object using Mustache.js. I wanted it to show two rows, however it's only showing the second row only. I suspect that the first row is being overwritten by the second when it's being bound again in the loop.

我如何解决这个问题?或者我应该遵循更好的结构?

How do I work my way around it? Or is there a better structure I should follow?

Javascript:

Javascript:

var text = '[{"Fullname":"John", "WorkEmail":"john@gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary@gmail.com"}]'
var obj = JSON.parse(text);

$(document).ready(function() {
        var template = $('#user-template').html();
        for(var i in obj)
        {
        var info = Mustache.render(template, obj[i]);
        $('#ModuleUserTable').html(info);
        }
}); 

模板:

<script id="user-template" type="text/template">
    <td>{{FullName}}</td>
    <td>{{WorkEmail}}</td>
</script>

表格:

<table border="1">
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
<tr id = "ModuleUserTable"> 
</tr> 
</table>


推荐答案

除了你自己的解决方案,你应该考虑使用小胡子为你重复这行:

In additon to your own solution, you should consider using mustache to repeat the row for you:

<script id="user-template" type="text/template">
{{#people}}
<tr>
    <td>{{FullName}}</td>
    <td>{{WorkEmail}}</td>
</tr>
{{/people}}
</script>

 

var text = '[{"Fullname":"John", "WorkEmail":"john@gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary@gmail.com"}]'
var obj = {people: JSON.parse(text)};

$(document).ready(function() {
    var template = $('#user-template').html();
    var info = Mustache.render(template, obj);
    $('#ModuleUserTable').html(info);
});

这篇关于JSON对象进入Mustache.js表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆