我的问题不太清楚,但我不知道如何解释。所以我有这样的list.json
function get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("GET", "mylist.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var o in d){
results.innerHTML +=
'<div class="'+d[o].place+'"><h2>'+d[o].name+'</h2><div class="gallery"></div></div>';
} //for(var o in d)
}
}
hr.send(null);
results.innerHTML = 'Please wait...';
&#13;
{
"product1":{
"name": "apple",
"place": "X",
"image": [ {"pic": 1, "review": "Review for pic 1"},
{"pic": 2, "review": "Review for pic 2"},
{"pic": 3, "review": "Review for pic 3"}
]
},
"product2":{
"name": "milk",
"place": "Y",
"image": [ {"pic": 1, "review": "Review for pic 1"},
{"pic": 2, "review": "Review for pic 2"}
]
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results">
</div>
<script>get_json();</script>
&#13;
您可以看到,根据地点X或Y,我将为每个产品创建一个X或Y类。在每个div中,我有产品名称和.gallery div。问题是:我如何定义&#34; pic&#34;和&#34;评论&#34;每个产品,并将它们添加到.gallery div中作为img和p。它支持最后看起来像这样。请帮我。我是json的新人。
<div id="results">
<div class="X">
<h2>Apple</h2>
<div class="gallery>
<img src="1.png">
<p>Review of pic 1</p>
<img src="2.png">
<p>Review of pic 2</p>
<img src="3.png">
<p>Review of pic 3</p>
</div>
</div>
<div class="Y">
<h2>Milk</h2>
<div class="gallery>
<img src="1.png">
<p>Review of pic 1</p>
<img src="2.png">
<p>Review of pic 2</p>
</div>
</div>
</div>
&#13;
答案 0 :(得分:0)
你需要一个双嵌套循环。例如:
for(var o in d)
{
results.innerHTML +=
'<div class="'+d[o].place+'"><h2>'+d[o].name+'</h2><div class="gallery">';
for(var i in d.image)
{
results.innerHTML += '<img src="' + d.image[i].pic + '.png" />';
results.innerHTML += '<p>' + d.image[i].review + '</p>';
}
results.innerHTML += '</div></div>';
}