2 回答
TA贡献1806条经验 获得超8个赞
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>
</title>
<style>
#t, tr, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<table id="t" cellpadding="10">
<tr>
<th>
Number
</th>
<th>
Name
</th>
<th>
Cost
</th>
</tr>
</table>
</body>
<script>
var number = ['PA1234', 'JM344', 'ML567'], name = ['John', 'Jessi', 'Monty'], costing = [30, 30, 30];
for(var i=0;i<3;i++) {
$("#t").append('<tr><td>' + number[i] + '</td><td>' + name[i] + '</td><td>' + costing[i] + '</td></tr>');
}
</script>
</html>
TA贡献2039条经验 获得超7个赞
必须改变你的第二个对象的一些东西,成本。我不认为你可以在不同的值上使用相同的键名称,你将无法迭代它们。现在您可以采取两种方法:
var data = [
{"number": "PA1234","name": "John"},
{"number": "JM344","name": "jessi"},
{"number": "ML567","name": "Monty"}
];
var costing = {
"cost0": 10,
"cost1": 20,
"cost2": 30,
};
document.addEventListener("DOMContentLoaded", () => {
const place = document.getElementById("place").firstElementChild
const table = document.createElement("table")
for(let i = 0; i < data.length; i++){
let tr = document.createElement("tr")
let tdNumber = document.createElement("td")
let tdName = document.createElement("td")
let tdCost = document.createElement("td")
tdNumber.innerText = data[i].number
tdName.innerText = data[i].name
tdCost.innerText = costing["cost"+i]
tr.appendChild(tdNumber)
tr.appendChild(tdName)
tr.appendChild(tdCost)
table.appendChild(tr)
}
place.appendChild(table)
})
但就我个人而言,我会将您的成本核算对象更改为:
var costing2 = [
10,20,30
]
并将 for 循环更改为:
for(let i = 0; i < data.length; i++){
let tr = document.createElement("tr")
let tdNumber = document.createElement("td")
let tdName = document.createElement("td")
let tdCost = document.createElement("td")
tdNumber.innerText = data[i].number
tdName.innerText = data[i].name
tdCost.innerText = costing2[i]
tr.appendChild(tdNumber)
tr.appendChild(tdName)
tr.appendChild(tdCost)
table.appendChild(tr)
}
其中place是div标签在html中的位置。这不是最好的解决方案,但它可以工作,如果你想要的话,也可以写下 html 代码:
<html>
<head>
<script src="./file.js"></script>
</head>
<body>
<div id="place">
<pre>
</pre>
</div>
</body>
</html>
- 2 回答
- 0 关注
- 128 浏览
添加回答
举报