我设法创建一个js mini项目,根据提供的任何(x,y)值构建表格;我的主要问题是,我想要3个表行,无论插入的值是什么,我都只得到一个。我对appendChild方法非常陌生,任何有关我如何以不同方式使用它们的额外信息都将不胜感激。
var submit = document.getElementById("smit");
var irow = document.getElementById("irow");
var icol = document.getElementById("icol");
// submission
submit.addEventListener("click", function() {
GenerateTable();
})
// functions to create values of r and c
function GenerateTable() {
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
var tblBody = document.createElement("tbody");
tblBody.appendChild(row);
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
tr {
width: 50px;
height: 30px;
border: 1px solid black;
}
td {
width: 50px;
height: 30px;
border: 1px solid black;
}
table {
border: 2px solid black;
}
<label>Rows</label>
<input type="number" id="irow">
<label>Cols</label>
<input type="number" id="icol">
<input type="submit" id="smit">
<table id="table">
</table>
答案 0 :(得分:2)
移动代码,在循环之外创建tbody
元素。
var submit = document.getElementById("smit");
var irow = document.getElementById("irow");
var icol = document.getElementById("icol");
// submission
submit.addEventListener("click", function() {
GenerateTable();
})
// functions to create values of r and c
function GenerateTable() {
var tblBody = document.createElement("tbody"); // moved out of the outer loop
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
&#13;
tr {
width: 50px;
height: 30px;
border: 1px solid black;
}
td {
width: 50px;
height: 30px;
border: 1px solid black;
}
table {
border: 2px solid black;
}
&#13;
<label>Rows</label>
<input type="number" id="irow">
<label>Cols</label>
<input type="number" id="icol">
<input type="submit" id="smit">
<table id="table">
</table>
&#13;