提问人:Criostoir Mac Tomás 提问时间:12/16/2020 最后编辑:marc_sCriostoir Mac Tomás 更新时间:12/16/2020 访问量:96
使用 AJAX 在 jQuery 中循环嵌套数组
Looping nested arrays in jQuery with AJAX
问:
我有一个 JSON 文件,我正在 AJAX 和 jQuery 中使用,它具有以下数据结构。
{
"status": 200,
"data": [
{
"date": "2020-09",
"name": "September 2020",
"days": [
{
"date": "2020-09-19",
"number": "19",
"day": "Wed"
},
{
"date": "2020-09-21",
"number": "21",
"day": "Fri"
},
{
"date": "2020-09-24",
"number": "24",
"day": "Tues"
},
{
"date": "2020-09-30",
"number": "30",
"day": "Sun"
}
]
},
{
"date": "2020-10",
"name": "October 2020",
"days": [
{
"date": "2020-10-24",
"number": "24",
"day": "Tues"
},
{
"date": "2020-10-30",
"number": "30",
"day": "Wed"
}
]
}
]
}
我想显示一个月,然后显示嵌套在该月份对象中的相应日期。
success: (response) => {
$("#date-time-picker").show();
response.data.forEach((month) => {
console.log(month.name);
$("#date-select-container").append(
'<p class="py-15 font-small__14 m-0">' +
month.name +
'</p><div class="d-flex flex-wrap date-picker justify-content-center light-blue-border--bottom pb-5 w-100"></div>'
);
month.days.forEach((days) => {
let dateSelectHtml =
'<label class="mb-0"><input type="radio" name="date" class="card-input-element" value="' +
days.date +
'" /><div class="card card-input light-blue-border px-10 py-20"><h2>' +
days.number +
'</h2><p class="booking-info__standard-color m-0">' +
days.day +
"</p></div></label>";
$(".date-picker").append(dateSelectHtml);
});
});
},
这是我按原样运行它时得到的结果。正如你所看到的,它遍历第一个月对象中的所有嵌套天数,但只遍历第二个月对象中正确的 2 天。
答:
0赞
Criostoir Mac Tomás
12/16/2020
#1
我让它起作用了。
对于那些遇到这个问题并有同样问题的人来说,问题是:
在第二个循环中,我没有正确识别父循环。
response.data.forEach((month) => {
$("#date-select-container").append(
'<p class="py-15 font-small__14 m-0">' +
month.name +
'</p><div class="d-flex flex-wrap date-picker justify-content-center light-blue-border--bottom pb-5 w-100" id="month-' +
month.date + // Here I have added the month.date as an ID for the child to identify it's parent in the next loop
'"></div>'
);
if (month.days.length) {
month.days.forEach((days) => {
let dateSelectHtml =
'<label class="mb-0"><input type="radio" name="date" class="card-input-element" value="' +
days.date +
'" /><div class="card card-input booking-info__standard-color light-blue-border px-20 m-10 py-20"><h2>' +
days.number +
'</h2><p class="booking-info__standard-color m-0">' +
days.day +
"</p></div></label>";
$("#month-" + month.date).append(dateSelectHtml); // And then I am identifying that here to append to the correct ID.
});
} else {
let noDays =
"<p>Unfortunately there are no days available for this month</p>";
$("#month-" + month.date).append(noDays);
}
});
评论
$(".date-picker")
选择具有该类的所有元素。所以在你的情况下,9月和10月的那个。 然后将添加到集合中的所有元素中,因此是“九月”和“十月”。您必须找到一种方法来仅引用您为当月添加的内容。.append()
dateSelectHtml
.date-picker
:last
.date-picker
.date-picker