【问题标题】:Unable to reference a dynamically created table using document.getElementById()无法使用 document.getElementById() 引用动态创建的表
【发布时间】:2021-03-11 21:33:17
【问题描述】:

我正在尝试使用 document.getElementById() 从 createHTMLTableFromTableObject() 之外的函数中引用该表。我创建了一个按钮,可以将对表中位置的引用打印到控制台,但我得到的只是一个错误。我显然没有正确引用表格,但我在网上找到的所有内容都表明这是它的完成方式。当我在 createHTMLTableFromTableObject() 中执行完全相同的控制台语句时,它被完美地引用了。我做错了什么,有什么方法可以正确引用表格吗?请注意,这是为表格随机生成信息的更广泛代码的一部分,我已将其删除并在每个单元格中将其替换为“-”。

<!DOCTYPE html>
<html>
<style>
    p,
input {
    font: 14px Verdana;
}

.code {
    margin-left: auto; 
    margin-right: auto;
    width: 50%;   
}

tr:nth-child(even) {background: #FFF}
tr:nth-child(odd) {background: rgb(228, 228, 228)}


.htmlTable {
    border: solid 2px #000;
    border-collapse: collapse;
    margin-left: auto; 
    margin-right: auto;
}

.thCell {
    border: solid 1px #000;
    border-collapse: collapse;
    padding: 8px 8px;
    background-color:rgb(136, 136, 136);
    font: 14px Verdana;
    color: black;
    font-weight: bold;
}

.thAlign {
    text-align: center;
}

.tdCell {
    border: solid 1px #000;
    border-collapse: collapse;
    padding: 8px 8px;
    font: 14px Verdana;
    color: black;
}

.tdTxtAlign {
    text-align: left;
}

.tdNumAlign {
    text-align: right;
}
</style>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>Convert JavaScript Object Data to HTML Table</title>
</head>

<body>
    <!-- View showing Table containing randonly generated data -->
    <!-- And a Button to generate another random table-->
    <div>
        <div style="padding: 20px; text-align: center;"><input type="button" onclick="createHTMLTableFromTableObject()"
                value="Create Table From JavaScript Object" /></div>
        <table style="padding: 20px;" id="showTableData"></table>

        <div style="padding: 20px; text-align: center;"><input type="button" onclick="testRef()"
            value="Test Reference to Table" /></div>

</div>
    <!-- Function to generate a JS Table Object, and a function to convert to HTML Table --> 
    <script>
        //
        // The table object - it is the data model!
        //
        var myTable = []; 

        //
        // generate random data to populate the table model (populates a JavaScript object)
        //
        function genNewTable(table, numRows) {
            for (i = 0; i < numRows; i++) {
                // generate table row with random data
                table.push({
                    "Student Name": "-",
                    "Student ID": "-",
                    "Assignment 1": "-",
                    "Assignment 2": "-",
                    "Assignment 3": "-",
                    "Assignment 4": "-",
                    "Assignment 5": "-",
                    "Average (%)": null
                });
                // calculate the average grade for the last generated record inserted into table
                numAssignments = -3; averageGrade = 0;
                studentRecord = table[table.length - 1];
                // get the keys for any column matching "assignment"
                // var assignmentKeys = Object.keys(studentRecord).filter((assignment) => /Assignment/.test(assignment));
                // get total grades (not averaged) just to see what you can do with filter
                // Object.keys(studentRecord).filter((assignment) => averageGrade += (/Assignment/.test(assignment))?studentRecord[assignment]:0);
                for (var column in studentRecord) {
                    if (/^Assignment/.test(column))
                        averageGrade += studentRecord[column]; 
                        numAssignments++;
                }
                averageGrade = Math.round(averageGrade / numAssignments);
                // set the final column to the average grade for the randomly generated grades
                studentRecord["Average (%)"] = averageGrade +"%";
            }
        }
        //
        // generate a table from the JavaScript (JSON) object
        //
        function createHTMLTableFromTableObject() {
            // generate a new table using random data
            myTable = []; genNewTable(myTable, 10);

            // extract the column headers from the current data model (using first row of data model)
            var colHeaders = Object.keys(myTable[0]);

            // create the <table> object for inserting into DOM
            var table = document.createElement("table");
            table.setAttribute("class", "htmlTable");

            // create the <table> header row first using extracted headers
            var tr = table.insertRow(-1);                  // create the row (at end of table)                
            for (var i = 0; i < colHeaders.length; i++) {
                var th = document.createElement("th");     // and the headers
                th.setAttribute("class", "thCell thAlign");     // add the styles
                th.innerHTML = colHeaders[i];
                tr.appendChild(th);
            }

            // add the data from the table object as rows
            for (var i = 0; i < myTable.length; i++) {
                tr = table.insertRow(-1); // insert row at end of table
                for (var j = 0; j < colHeaders.length; j++) {
                    var tabCell = tr.insertCell(-1); // insert at end of row
                    if (j<2) {
                        tabCell.setAttribute("class", "tdCell tdTxtAlign");
                    } else {
                        tabCell.setAttribute("class", "tdCell tdNumAlign");
                        tabCell.contentEditable = true;
                    }
                    tabCell.innerHTML = myTable[i][colHeaders[j]];
                    //console.log(table.rows[i+1].cells[j]);        <---------- PERFECT REFERENCE
                }
            }
            // now update the table view (container)
            var viewContainer = document.getElementById("showTableData");
            viewContainer.innerHTML = ""; // reset
            viewContainer.appendChild(table); // add the table
        }
        
        function testRef()
        {
            var table = document.getElementById("showTableData");
            console.log(table.rows[0].cells[1]);
        }

</script>
</body>
</html>

【问题讨论】:

  • 你得到什么样的错误?
  • tabletest.html:161 Uncaught TypeError: Cannot read property 'cells' of undefined at testRef (tabletest.html:161) at HTMLInputElement.onclick (tabletest.html:70)
  • 请注意,在组装表格的函数中执行 console.log 语句时,我没有收到此错误
  • 您是先点击 testRef 按钮吗?因为那样的话 dom 中当然没有表。
  • 不,我在生成它之前

标签: javascript html css json function


【解决方案1】:

这是因为您将生成的表放入已经存在的表中(id:showTableData),然后您正在调用该表。

它会返回类似&lt;table id="showTableData"&gt;&lt;table class="htmlTable"&gt;&lt;/table&gt;&lt;/table&gt;

并且您想解决第二个或更好的问题,但不要在另一个表中放置一个表:)

function testRef()
{
    var table = document.querySelector(".htmlTable");
    console.log(table.rows[0].cells[1]);
}

这是一个快速修复(证明),但您应该将生成的表直接生成到容器中。

编辑 1:回答更多问题

在 javascript 中更改

table.setAttribute("class", "htmlTable");

table.setAttribute("id", "showTableData");

如果您需要该类名,也可以同时保留两者。

接下来是当前地址第一个表的这一行

var viewContainer = document.getElementById("showTableData");

改成

var viewContainer = document.getElementById("showTableData_container");

最后是 HTML

<table style="padding: 20px;" id="showTableData"></table>

到这里

<div style="padding: 20px;" id="showTableData_container"></div>

你现在可以使用原来的测试功能了

function testRef()
{
    var table = document.getElementById("showTableData");
    console.log(table.rows[0].cells[1]);
}

【讨论】:

  • 好的,我明白了,谢谢,这行得通,但你如何将它直接生成到容器中?
  • 没问题,我已经进行了编辑和解释。
【解决方案2】:

在你的代码中你写道:

        // create the <table> object for inserting into DOM
        var table = document.createElement("table");
        table.setAttribute("class", "htmlTable");

而且这个表和id="showTableData"的表不一样

要获取使用函数 createHTMLTableFromTableObject 创建的表的第一行的内容:

    function testRef(){
        var table = document.querySelector(".htmlTable");
        console.log(table.rows[0].cells[1]);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    相关资源
    最近更新 更多