我是第一次使用 Mustache JS,并对实现我想要的效果的最佳方法有疑问。我有以下页面,其中有几个以相同方式设置的 div,但需要获取不同的内容。
这是我到目前为止得到的:
<script id="mustacheTemplate1" type="text/template">
<div class="{{box_cols}}">
<div class="box box-{{box_color}}">
<h2 class="box-title">{{box_title}}</h2>
{{box_content}}
</div>
</div>
</script>
<div class="target-output1"></div>
<script type="text/javascript">
var template1 = $("#mustacheTemplate1").html();
var targetContainer = $(".target-output1");
var shows = {
"box_cols": "col-lg-3 col-md-6 col-sm-6",
"box_color": "blue",
"box_title": "Title goes here",
"box_content": "Content goes here",
};
var html = Mustache.to_html(template1, shows);
$(targetContainer).html(html);
</script>
这填充了我的第一个 div,这就是我想要的。我可以重复此操作并将 target-output1 复制到 target-output2、target-output3 等。但我想知道是否有更好或更有效的方法?
我不知道这是否重要,但我将在某些 div 内容中使用 Google Charts。
最佳答案
假设您拥有用生成的内容填充所需的所有 div,您可以使用循环
var template1 = $("#mustacheTemplate1").html();
[
{
"box_cols": "col-lg-3 col-md-6 col-sm-6",
"box_color": "blue",
"box_title": "Title goes here",
"box_content": "Content goes here",
},
{
"box_cols": "col-lg-3 col-md-6 col-sm-6",
"box_color": "red",
"box_title": "Another Title",
"box_content": "Totally different content goes here",
}
//, ... etc
].forEach(function(data, i) {
$('.target-output' + (i+1)).html(Mustache.to_html(template1, data))
})
关于javascript - mustache JS : fill multiple divs with different content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44237148/