javascript - TypeError:向表中添加行时表为空
问题描述
我正在尝试创建元素并将其添加到表中。
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
我
真的不知道为什么会这样说,因为我对 JavaScript 还很陌生。我感谢您的帮助。addRow line 30:5
let table = document.getElementById(tableID);
解决方案
您正在制作一个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>
推荐阅读
- c# - 如何从 JsonConvert.PopulateObject 中排除某些基本类型或接口中不存在的属性?
- sql - 如何让 PostgreSQL 给我类似 MySQL SHOW COLUMNS 的结果?
- database - 当字段和值存在时,MongoDB find() 查询不返回任何内容
- html - 如何解决在 HTML 和 CSS 中分离三个并排元素的问题
- lua - Lua Coroutines resume:'resume'的错误参数#-1(预期的布尔值)
- swift - 导航栏第一次没有正确充电
- c# - C# - 哪个接口未注册,如何注册?
- grafana - 即使指标很好,Grafana 也会发出警报
- css - 隐藏溢出时的额外按钮
- php - 如何根据 comming 链接更改数据库值