考虑以下js-loop:
for (var i=0;i<diff;++i){
for (var j=0; j<old_col_num; ++j){
var t_col = document.createElement("td");
//the following line throws an error:
t_body.children[old_row_num+1+i].appendChild(t_col);
}
}
我收到的错误消息如下:
Uncaught TypeError: Cannot read property 'appendChild' of undefined(…)
我不明白为什么它不起作用。如果我输入一个固定的数字而不是&#34; old_row_num + 1 + i&#34;没有错误(但我的程序需要灵活性)。
更新:
整个功能如下:
function change_dim_r(diff) {
var old_row_num = t_body.childElementCount;
var old_col_num = t_body.children[0].childElementCount;
for (var i=0; i<diff; ++i){
var new_t_row = document.createElement("tr");
t_body.appendChild(new_t_row);
}
for (var i=0;i<diff;++i){
for (var j=0; j<old_col_num; ++j){
var t_col = document.createElement("td");
t_body.children[old_row_num+1+i].appendChild(t_col);
}
}
}
答案 0 :(得分:1)
我相信您的旧行号不准确。
var old_row_num = t_body.children.childElementCount;
如果您想要行数,那么.children
就行了。
function change_dim_r(diff) {
var t_body = document.querySelector("tbody");
var old_row_num = t_body.childElementCount;
var old_col_num = t_body.children[0].childElementCount;
for (var i = 0; i < diff; ++i) {
var new_t_row = document.createElement("tr");
t_body.appendChild(new_t_row);
}
for (var i = 0; i < t_body.childElementCount; ++i) {
var t_row = t_body.children[i];
for (var j = t_row.childElementCount; j < t_body.childElementCount; ++j) {
var t_col = document.createElement("td");
t_row.appendChild(t_col);
}
}
}
change_dim_r(10);
&#13;
<table border="1" cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
&#13;