我需要从 JSON 获取值并将它们显示在 HTML 表格中。
下面是我的 JSON:
[
{
"id": "3",
"title": "Doing Business In...",
"businessSubjectAreas": [
{
"businessSubjectArea": "Market and Sell Products/Service"
},
{
"businessSubjectArea": "Deliver Products/Services"
},
{
"businessSubjectArea": "HR"
},
{
"businessSubjectArea": "Legal"
},
{
"businessSubjectArea": "Finance"
},
{
"businessSubjectArea": "Tax"
},
{
"businessSubjectArea": "Treasury"
},
{
"businessSubjectArea": "IT"
}
],
"attachmentFiles": [
{
"fileName": "Australia.html",
"url": ""
}
],
"error": null
},
{
"id": "65",
"title": "Dialing Instructions",
"businessSubjectAreas": [
{
"businessSubjectArea": "Administrative"
}
],
"attachmentFiles": [
],
"error": null
},
{
"id": "132",
"title": "WA - Western Australia - Drilling Fluid Management",
"businessSubjectAreas": [
{
"businessSubjectArea": "Market and Sell Products/Service"
},
{
"businessSubjectArea": "Deliver Products/Services"
},
{
"businessSubjectArea": "Legal"
}
],
"attachmentFiles": [
{
"fileName": "",
"url": ""
}
],
"error": null
},
{
"id": "133",
"title": "WA - Natural gas from shale and tight rock - Overview of WA regulatory framework",
"businessSubjectAreas": [
{
"businessSubjectArea": "Market and Sell Products/Service"
},
{
"businessSubjectArea": "Deliver Products/Services"
},
{
"businessSubjectArea": "Legal"
}
],
"attachmentFiles": [
{
"fileName": "",
"url": ""
}
],
"error": null
}
]
下面是我的 jQuery 代码:
$.each(json, function(index, value) {
$("#id_kbdata").append(
" <tr><td style='text-align:left;font-family:arial;padding:5px 10px;border-bottom:1px solid #ccc;border-right:1px solid #ccc;width:33%;'>" +
this.title +
"</td><td style='text-align:left;font-family:arial;padding:5px 10px;border-bottom:1px solid #ccc;border-right:1px solid #ccc;width:33%;'> "
+
"<ul>" +
$.each(this.businessSubjectAreas, function(index, value) {
"<li>" + this.businessSubjectArea + "</li>"
}) +
"</ul>" +
" </td><td style='text-align:left;font-family:arial;padding:5px 10px;border-bottom:1px solid #ccc;border-right:1px solid #ccc;width:33%;'> "
+
"<ul>" +
$.each(this.attachmentFiles, function(index, value) {
"<li><a href=" + this.url + ">" + this.fileName + "</a></li>"
}) +
"</ul>" +
" </td></tr>"
);
});
在这里,我无法通过每个内部循环(如 this.businessSubjectArea
)从 JSON 获取值,我将这些值作为 [object Object]、this.title
获取工作正常。我已从 JSON 中删除了值,因为它是敏感数据。
如何使用 jQuery 代码访问 this.businessSubjectArea
、this.url
等值?
最佳答案
使用值
作为内部项
$.each(this.businessSubjectAreas, function(index, value) {
"<li>" + value.businessSubjectArea + "</li>"
})
对于attachmentFiles
也是如此
$.each(this.attachmentFiles, function(index, value) {
"<li><a href=\"" + value.url + "\">" + value.fileName + "</a></li>"
})
关于javascript - 使用每个循环从嵌套 json 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726709/