我正在尝试创建元素并将其添加到表中。
function flaeche() {
let tableID = "testTable";
let x = document.createElement("TABLE");
x.setAttribute("id", tableID);
for (let argument of arguments) {
let radius = ((argument*argument)*Math.PI).toFixed(2);
addRow(argument,radius,tableID);
}
}
function addRow(value, result, tableID){
let table = document.getElementById(tableID);
let row = table.insertRow(0);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
cell1.innerHTML = value;
cell2.innerHTML = result;
}
如果我尝试运行代码,则会收到以下错误:
TypeError: table is null
at addRow line 30:5
这对应于
let table = document.getElementById(tableID);
我真的不知道为什么这么说,因为我对 JavaScript 还很陌生。感谢您的帮助。
最佳答案
您正在创建一个 table
元素,但并未将其添加到页面中。如果您想稍后使用 document.getElementById()
找到该表,则需要将该表实际放置在 DOM 中的某个位置。例如:
function flaeche() {
let tableID = "testTable";
let x = document.createElement("TABLE");
x.setAttribute("id", tableID);
// add table to the page somewhere
// for example in the div named container
let container = document.getElementById("container")
container.appendChild(x)
for (let argument of arguments) {
let radius = ((argument*argument)*Math.PI).toFixed(2);
addRow(argument,radius,tableID);
}
}
function addRow(value, result, tableID){
let table = document.getElementById(tableID);
let row = table.insertRow(0);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
cell1.innerHTML = value;
cell2.innerHTML = result;
}
flaeche(5, 6)
td {
border: 1px solid #ddd;
padding: 1em;
}
<div id="container"></div>
关于javascript - 类型错误 : table is null when adding row to table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53806310/