这是我的jsfiddle
http://jsfiddle.net/v8ngoyur/3/
物品2没有任何结壳,因为结壳长度仅为1,与第1项有关
但是第2项仍然显示了Crustings Value
请告诉我如何避免这种情况?
这是我的代码
var ordersplitjson =
{
"vendors": {
"T1": [
{
"name": "Raj Shop",
"leaf": [
{
"crusts": [
{
"name": "Quantity 1",
"value": [
"Crusts a",
"Crusts b"
]
}
],
"toppings": [
{
"name": "Quantity 1",
"value": [
"Topp a",
"Topp b"
]
},
{
"name": "Quantity 2",
"value": [
"Topp a",
"Topp b"
]
}
]
}
]
}
]
}
}
var divhtmltoppcrust = '';
for (var i = 0; i < ordersplitjson.vendors.T1.length; i++)
{
var totalitemprice = 0;
var vendorname = ordersplitjson.vendors.T1[i].name;
var vendoritems = ordersplitjson.vendors.T1[i].leaf;
var vendoritemlen = ordersplitjson.vendors.T1[i].leaf.length;
for (var j = 0; j < vendoritems.length; j++)
{
var toppins = vendoritems[j].toppings;
var crusts = vendoritems[j].crusts;
if (toppins.length > crusts.length)
{
for (var l = 0; l < toppins.length; l++)
{
for (var k = 0; k < crusts.length; k++)
{
var toppingsul = '<ul>';
$.each(toppins[l].value, function(i, text) {
if (text != '' && text != undefined)
{
toppingsul += "<li>" + text + "</li>";
toppingsul += "</ul>";
}
});
var crustsul = '<ul>';
$.each(crusts[k].value, function(h, texter) {
if (texter != '' && texter != undefined)
{
crustsul += "<li>" + texter + "</li>";
crustsul += "</ul>";
}
});
var valuesss = l + 1;
divhtmltoppcrust += '<div class="orders-row"><aside class="left-order"><i>item ' + valuesss + ' Toppings ' + toppingsul + ' Crustings ' + crustsul + '</i></aside></div>';
}
}
}
}
}
答案 0 :(得分:1)
只需添加条件if (l < crusts.length)
即可添加crustsul
。在else
中,您应该像下面这样空crustsul
,
if (l < crusts.length) {
var crustsul = '<ul>';
$.each(crusts[l].value, function (h, texter) {
if (texter != '' && texter != undefined) {
crustsul += "<li>" + texter + "</li>";
crustsul += "</ul>";
}
});
} else {
var crustsul = '';
}
见这个JSFIDDLE DEMO
更新:1
要获得循环的最大长度,您可以在这样的条件下检查它,
if (toppins.length > crusts.length)
var max = toppins.length;
else
var max = crusts.length;
现在,您可以使用变量max
作为循环的最大长度。
看到这个更新-1 JSFIDDLE DEMO
更新:2
只需添加条件if (l < toppins.length)
即可添加toppingsul
。在else
中,您应该像下面这样空toppingsul
,
if (l < toppins.length) {
var toppingsul = '<ul>';
$.each(toppins[l].value, function (i, text) {
if (text != '' && text != undefined) {
toppingsul += "<li>" + text + "</li>";
toppingsul += "</ul>";
}
});
} else {
var toppingsul = '';
}
看到这个更新的2 JSFIDDLE DEMO