JSON对象进入Mustache.js表

Jos*_*Tan 5 javascript json html-table mustache

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

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

使用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);
        }
}); 
Run Code Online (Sandbox Code Playgroud)

模板:

<script id="user-template" type="text/template">
    <td>{{FullName}}</td>
    <td>{{WorkEmail}}</td>
</script>
Run Code Online (Sandbox Code Playgroud)

表:

<table border="1">
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
<tr id = "ModuleUserTable"> 
</tr> 
</table>
Run Code Online (Sandbox Code Playgroud)

Jos*_*Tan 6

我想通了,而不是

$('#ModuleUserTable').html(info);
Run Code Online (Sandbox Code Playgroud)

它应该是 :

$('#ModuleUserTable').append(info);
Run Code Online (Sandbox Code Playgroud)

模板应该是:

<script id="user-template" type="text/template">
<tr>
    <td>{{FullName}}</td>
    <td>{{WorkEmail}}</td>
</tr>
</script>
Run Code Online (Sandbox Code Playgroud)

和ID不应该在表行标记上.相反它应该在桌子上:

<table border="1"  id = "ModuleUserTable>
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)

它附加的时刻,它会在表中添加一个带有JSON数据的新行.


RoT*_*oRa 6

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

<script id="user-template" type="text/template">
{{#people}}
<tr>
    <td>{{FullName}}</td>
    <td>{{WorkEmail}}</td>
</tr>
{{/people}}
</script>
Run Code Online (Sandbox Code Playgroud)

 

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);
});
Run Code Online (Sandbox Code Playgroud)