0

我想知道如何使用把手迭代以下数据对象。

这是它的输出:

image2.png | title2 
image3.png | title3 

我想达到的目标:

image1.png | title1
image2.png | title2 
image3.png | title3 

数据

var data = {
  "item": [{ // item with one image
      "src" : "image1.png",
      "title" : "title1"
  }],
  "item": [{ // item with two or more images
      "src" : "image2.png",
      "title" : "title2"
  },
  {
      "src" : "image3.png",
      "title" : "title3"
  }]
}

var template = Handlebars.compile($("#data-template").text());
var html = template(data);
$('#placeholder').html(html);

模板

<div id="placeholder"></div>
<script type="text/x-handlebars" id="data-template">
    {{#item}}
       {{src}} | {{title}} <br>
    {{/item}}
</script>

http://jsfiddle.net/88CwB/

4

1 回答 1

1

您的 JSON 无效。

车把只能看到 2 个项目。

var data = {
  "item": [{ // item with one image
      "src" : "image1.png",
      "title" : "title1"
  }],
  "item": [{ // item with two or more images
      "src" : "image2.png",
      "title" : "title2"
  },
  {
      "src" : "image3.png",
      "title" : "title3"
  }]
}


var template = Handlebars.compile($("#data-template").text());
var html = template(data);
$('#placeholder').html("<p>" + data.item + "</p>");

见:http: //jsfiddle.net/hZQnD/1/

data您可以通过使您的对象仅包含 1 个对象来修复它item,该对象可能包含 3 个项目的数组。

var data = {
  "item": [{ // item with 3 images
      "src" : "image1.png",
      "title" : "title1"
  },
  {
      "src" : "image2.png",
      "title" : "title2"
  },
  {
      "src" : "image3.png",
      "title" : "title3"
  }]
}


var template = Handlebars.compile($("#data-template").text());
var html = template(data);
$('#placeholder').html(html);

见:http: //jsfiddle.net/75UzZ/1/

您还可以通过使您的数据对象成为具有属性的对象数组item并在 for 循环中迭代它们来修复它:

var data = [{
    "item": [{ // item with one image
        "src" : "image1.png",
        "title" : "title1"
    }]
  },{
    "item": [{ // item with two or more images
        "src" : "image2.png",
        "title" : "title2"
    },
    {
        "src" : "image3.png",
        "title" : "title3"
    }]
}];

var template = Handlebars.compile($("#data-template").text());
var html = ""
for( var i = 0; i < data.length; ++i ){
  html += template(data[i]);
}
$('#placeholder').html(html);

见:http: //jsfiddle.net/dFmQG/2/

于 2013-05-31T00:22:50.577 回答