我在javascript中遇到了一个问题,我想在表格中显示一个列Success/Fail
,但是他们在表格中显示了两列。它们不会在Success/Fail
列中显示正确的值。
我该怎么办?有没有人帮我?
var responseList = [{
"summary": {
"template_name": "test",
"success": "2",
"fail": "1",
},
"summary": {
"template_name": "test",
"success": "3",
"fail": "2",
},
}];
var table = document.querySelector('#my-table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
for (var i = 0; i < responseList.length; i++) {
var tr = tbody.insertRow();
var summary = responseList[i]["summary"];
console.log(summary);
for (var key in summary) {
if (summary.hasOwnProperty(key)) {
console.log(key + " -> " + summary[key]);
var td = tr.insertCell();
td.innerHTML = summary[key];
if(key == "success" || key == "fail"){
// console.log("success",summary[key]);
// console.log("fail",summary[key]);
var td = tr.insertCell();
td.innerHTML = `${summary[key]} Successful / ${summary[key]} Failed`;
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<table id="my-table" border="0">
<thead>
<tr>
<th>Template name</th>
<th>Success</th>
<th>Success/Fail</th>
<th>Fail</th>
<th>Success/Fail</th>
</tr>
</thead>
</table>
</body>
</html>
发布于 2020-07-17 05:28:29
您的尝试对于它需要做的事情来说有点复杂,在循环中迭代摘要对象的键来构建表没有太大的价值。直接访问密钥要简单得多,就像我在下面做的那样。
var responseList = [
{
"template_name": "test",
"success": "2",
"fail": "1",
},
{
"template_name": "test",
"success": "3",
"fail": "2",
},
];
var table = document.querySelector('#my-table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
responseList.forEach(summary => {
var tr = tbody.insertRow();
tr.insertCell().innerHTML = `${summary.template_name}`
tr.insertCell().innerHTML = `${summary.success}`
tr.insertCell().innerHTML = `${summary.fail}`
tr.insertCell().innerHTML = `${summary.success}/${summary.fail}`
})
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<table id="my-table" border="0">
<thead>
<tr>
<th>Template Name</th>
<th>Success</th>
<th>Fail</th>
<th>Success/Fail</th>
</tr>
</thead>
</table>
</body>
</html>
https://stackoverflow.com/questions/62947317
复制相似问题