我尝试让页面向每个表添加行和五个单元格,但是我遇到了一些问题。我首先将该行附加到表格中,然后循环遍历并向每行添加五个单元格,但是每当我在网络浏览器中运行它时,它都会生成以下内容:
我希望单元格成为表格行的子行。
function addRows(ramnt) {
if(ramnt > 0){
var cellcount = 5;
var tccount = 0;
table.append('<tr>');
console.log('Appended <tr>');
while(tccount < cellcount){
tccount = tccount + 1;
table.append('<td id="Cell-' + tccount + '" class="gencell"></td>');
}
if (tccount = cellcount){
table.append('</tr>');
ramnt = ramnt - 1;
addRows(ramnt);
}
}
}
console.log('Working');
var table = $('Table');
addRows(5);
最佳答案
我建议让你的函数更加动态一些。这是我的建议:
function addRows(rc, to) {
if(rc > 0){
var cellcount = 5;
for(var i = 0; i < rc; i++){
var row = $("<tr>", { id: "Row-" + i });
for(var c = 0; c < cellcount; c++){
row.append("<td id='Cell-" + c + "' class='gencell'></td>");
}
to.append(row);
console.log("Row " + i + " created");
}
return true;
} else {
return false;
}
}
然后您可以像这样传递行数和表对象:
addRows(5, $("table"));
正如我所说,我建议您像这样设置 table :
<table id="myTable"></table>
这样,如果您稍后添加另一个表或执行不同的操作,您仍然可以使用相同的代码:
addRows(5, $("#myTable"));
工作示例:https://jsfiddle.net/Twisty/Lysr2n5v/
您可以进一步编写函数以接受 X 行数、每行 N 单元格数以及表对象:https://jsfiddle.net/Twisty/Lysr2n5v/2/
function addRows(rc, cc, to) {
if(rc > 0){
for(var i = 0; i < rc; i++){
var row = $("<tr>", { id: "Row-" + i });
for(var c = 0; c < cc; c++){
row.append("<td id='Cell-" + c + "' class='gencell'></td>");
}
to.append(row);
console.log("Row " + i + " created");
}
return true;
} else {
return false;
}
}
关于javascript - 添加表格行和单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280605/