javascript - 类型错误 : table is null when adding row to table

标签 javascript

我正在尝试创建元素并将其添加到表中。

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/

相关文章:

javascript - 使用javascript在Enter键上提交表单

javascript - 在 Karma/Mocha 中加载 Json fixture

javascript - 将 getComputedStyle 与 jsdom 一起使用

javascript - 为什么 ng-show 不起作用?

javascript - 尝试使用 Javascript Onclick 事件创建 ActiveX Template Coach (TCard) 对象

javascript - 是否可以在CSS3或Javascript中将字母映射到圆柱体或球体?

多个网络应用程序之间的 JavaScript 本地存储?

javascript - 理论 JavaScript 事件运行时

JavaScript 中的 PHP 函数 crypt()

javascript - 如何在新窗口中创建 HTML 表单