我目前正在使用类似于以下示例(简化版)的 for 循环将 JSON 结果写入页面:
var output = "";
for (i in response) {
var ID = response[i].ID
var name = response[i].name
output += "<div id=\""+ID+"\">"+name+"</div>"
}
$("#allResults").html(output);
输出变量变得臃肿和困惑。有没有什么方法可以在不需要 ""的情况下写入输出变量,因为插入变量和稍后修改代码特别困难?
最佳答案
试试下面的 HandlebarJS
模板片段。
包括这个:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
Handlebars 模板:
<script id="name-template" type="text/x-handlebars-template">
{{#each people}}
<div id="{{ID}}">{{name}}.</div>
{{/each}}
</script>
HTML:
<div class="content-placeholder"></div>
jQuery 和模板编译:
$(function () {
// Grab the template script
var theTemplateScript = $("#name-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
// This is the default context, which is passed to the template
var context = {
people: [
{ ID: 1000, name: 'Simpson' },
{ ID: 1001, name: 'Griffin' },
{ ID: 1002, name: 'Cartman' },
{ ID: 1003, name: 'McCormick' }
]
};
// Pass our data to the template
var theCompiledHtml = theTemplate(context);
// Add the compiled html to the page
$('.content-placeholder').append(theCompiledHtml);
});
关于javascript - 在 for 循环中编写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34583597/