Javascript 如何从json文件(把手)创建html列表

Javascript 如何从json文件(把手)创建html列表,javascript,json,handlebars.js,Javascript,Json,Handlebars.js,我有一个空的待办事项列表: <ul class="list"> </ul> 因此,我有以下javascript,它使用把手来模板化: <script> jQuery.getJSON("http://myurl/tasks.json", function(data){ var source = $("#tasks-template").html(); var template = Handlebars.compile

我有一个空的待办事项列表:

<ul class="list">

</ul>
因此,我有以下javascript,它使用把手来模板化:

 <script>    
    jQuery.getJSON("http://myurl/tasks.json", function(data){  
    var source   = $("#tasks-template").html();
    var template = Handlebars.compile(source);
      $.each(data) function() {
         var context = data;
         var show    = template(context);
        $(".list").html(show);
      });
    });         
    </script>

jQuery.getJSON(“http://myurl/tasks.json“,函数(数据){
var source=$(“#任务模板”).html();
var template=handlebar.compile(源代码);
$.each(数据)函数(){
var上下文=数据;
var show=模板(上下文);
$(“.list”).html(show);
});
});         
我的把手模板:

  <script id="tasks-template" type="text/x-handlebars-template">
    <li>
        <div>{{title}}</div>
    </li>
  </script>

  • {{title}}
  • 它不会在我的html中为json中的每个标题创建li

    我错过了什么


    谢谢

    对JSON中接收到的数组的每个对象进行迭代时,必须使用this而不是data来访问该对象。 数据是整个数组,是要检索title属性的当前对象:

    $.each(data, function() {
         var context = this;
         var show    = template(context);
        $(".list").append(show);
      });
    
    还可以将html方法更改为append,以避免覆盖内容

    问候

    $.each(data, function() {
         var context = this;
         var show    = template(context);
        $(".list").append(show);
      });