首页 > 解决方案 > 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:5let 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>


推荐阅读