【发布时间】: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