javascript - 在 for 循环中编写代码

标签 javascript jquery

我目前正在使用类似于以下示例(简化版)的 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/

相关文章:

jquery - 仅在 Safari 中显示跨度的奇怪高度问题

javascript - 尝试更改音量时出现 IndexSizeError

javascript - 如何缓存同一用户重复调用的 AngularJS 指令?

javascript - setAttribute 不起作用

javascript - NodeJS循环模块应用程序结构

javascript - 使用 jquery 和 ajax 将 json 对象发布到 mvc Controller

javascript - 如何自动将allowfullscreen添加到每个新的iframe

java - Nashorn 中的评估函数是否可从不同线程重用?

javascript - 如何在 jQuery 插件回调中使用 'this'?

javascript - xmlHttpRequest 出现 Phonegap 错误