我有一个代码来迭代代码,并希望通过比较类别来获取产品的项目: 如果category是“car”,那么该数组中的产品应该使用索引而不是按名称进行迭代
HTML
<ul class="menulist"></ul>
<div class="content"></div>
JS
var jsonData;
$(document).ready(function () {
$.ajax({
url: "product.json",
dataType: "json",
error: function () {
},
success: getData
});
function getData(data) {
alert(data)
for (i = 0; i < data.length; i++) {
var menulistdata = data[i].category,
menulist = '<li class="" data-att="' + menulistdata + '">' + menulistdata + '</li>'
$(".menulist").append(menulist);
}
$('.menulist li').on('click', function () {
var list = $(this).text();
for (i = 0; i < data.length; i++) {
alert(i)
var productData = data[i].products;
if (data[i].category == list) {
$(".content").append(productData.BMG[i].image + productData.BMG[i].date + productData.BMG[i].size);
}
}
})
}
});
JSON
[
{
"category":"car",
"products": {
"BMG" : [{
"image" : "images/cars/BMW.jpg",
"date": "5-May-2015",
"type": "JPGE image",
"size": "1132 KB"
}],
"verna":[{
"image" : "images/cars/Verna.jpg",
"date": "5-May-2015",
"type": "JPGE image",
"size": "1132 KB"
}]
}
},
{
"category":"Nature",
"products": {
"Nature Mood At Night" : [{
"image" : "images/nature/Night.jpg",
"date": "5-May-2015",
"type": "JPGE image",
"size": "1132 KB"
}],
"Snowfall on Hut":[{
"image" : "images/nature/Hut.jpg",
"date": "5-May-2015",
"type": "JPGE image",
"size": "1132 KB"
}]
}
}
]
答案 0 :(得分:2)
data[0].products
是object类型 - 您不能通过索引迭代对象,只能通过命名键。使用 for..in语句迭代对象。
for( var key in data[0].products ) {
console.log( data[0].products[key] );
}
请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
答案 1 :(得分:0)
据我所知,您想要追加所有汽车物业。所以这里是代码fiddle
$('.menulist li').on('click', function () {
var list = $(this).text();
for (i = 0; i < data.length; i++) {
var productData = data[i].products;
if (data[i].category == list) {
for(z in productData){
for(x in productData[z][0]){
$(".content").append(productData[z][0][x])
}
$(".content").append('<br>')
}
}
}
})