我有一个多维数组,不会填充所有元素。我想将该数组的内容输出到HTML表中。我目前有这个:
for (var basketRowJuice = 0; basketRowJuice < 10; basketRowJuice++){
var outputName = "";
outputName = (basketArray[0][basketRowJuice]);
document.getElementById("basketJuiceName" + basketRowJuice).innerHTML = outputName;
}
for (var basketRowQuant = 0; basketRowQuant < 10; basketRowQuant++){
var outputQuant = 0;
outputQuant = (basketArray[1][basketRowQuant]);
document.getElementById("basketJuiceQuant" + basketRowQuant).innerHTML = outputQuant;
}
for (var basketRowPrice = 0; basketRowPrice < 10; basketRowPrice++){
var outputPrice = 0;
outputPrice = (basketArray[2][basketRowPrice]);
document.getElementById("basketJuicePrice" + basketRowPrice).innerHTML = outputPrice;
}
HTML表格:
<table id="basket" cellpadding="0" cellspacing="0" summary="This table lists the items you have in your shopping basket">
<caption>Your basket</caption>
<tr>
<th scope="col">Juice name</th>
<th scope="col">Number of crates</th>
<th scope="col">Total price</th>
</tr>
<tr>
<td id="basketJuiceName0"></td>
<td id="basketJuiceQuant0"></td>
<td id="basketJuicePrice0"></td>
</tr>
<tr>
<td id="basketJuiceName1"></td>
<td id="basketJuiceQuant1"></td>
<td id="basketJuicePrice1"></td>
</tr>
<tr>
<td id="basketJuiceName2"></td>
<td id="basketJuiceQuant2"></td>
<td id="basketJuicePrice2"></td>
</tr>
<tr>
<td id="basketJuiceName3"></td>
<td id="basketJuiceQuant3"></td>
<td id="basketJuicePrice3"></td>
</tr>
<tr>
<td id="basketJuiceName4"></td>
<td id="basketJuiceQuant4"></td>
<td id="basketJuicePrice4"></td>
</tr>
<tr>
<td id="basketJuiceName5"></td>
<td id="basketJuiceQuant5"></td>
<td id="basketJuicePrice5"></td>
</tr>
<tr>
<td id="basketJuiceName6"></td>
<td id="basketJuiceQuant6"></td>
<td id="basketJuicePrice6"></td>
</tr>
<tr>
<td id="basketJuiceName7"></td>
<td id="basketJuiceQuant7"></td>
<td id="basketJuicePrice7"></td>
</tr>
<tr>
<td id="basketJuiceName8"></td>
<td id="basketJuiceQuant8"></td>
<td id="basketJuicePrice8"></td>
</tr>
<tr>
<td id="basketJuiceName9"></td>
<td id="basketJuiceQuant9"></td>
<td id="basketJuicePrice9"></td>
</tr>
</table>
但是,如果我的数组只填充在[0] [9],[1] [9]和[2] [9]列中,那么在输出之前,我的HTML结果会出现一大块空行。任何人都可以提出更好的方法吗?也许这样我的javascript为每个填充的数组元素插入一个表行?
我是编程的新手所以请原谅我毫无疑问的冗长和不雅的代码。
谢谢你, 乔恩
答案 0 :(得分:1)
您可能想要在循环中更像以下内容。
var outputPrice = basketArray[2][basketRowPrice];
if (outputPrice) {
// do something here. the if statement will be true for non-null, non-empty, non-zero values of the var outputPrice.
}
我还会注意到你可以将你的3个循环替换为:
for (var j = 0; j < 10; j++) {
for (var i = 0; i < 3; i++) {
var outputName = basketArray[i][j];
var outputQuant = basketArray[1][basketRowQuant];
//.. do the rest of the code
}
}
最后一步是删除硬编码的HTML并动态生成它,以下是没有检查的,所以它可能有点偏差,查找DOM方法。
var tbody = document.getElementById('basket').tbodies[0];
for (var j = 0; ...) {
var tr = document.createElement('tr');
tbody.appendChild(tr);
for (var i = 0; ..) {
var td = document.createElement('td');
td.innerHTML = ...;
tr.appendChild(td);
}
}