我期望此代码检索数组中的所有对象,并在“添加”按钮位于的行之前的行中显示它们。我没有看到显示的项目?下面是代码无法在HTML表格中显示数组元素
脚本:
var addButton = document.getElementById("add-button");
var textArea = document.getElementById("text");
//to display items
var myArray = [{
"name": "aaa",
"level": "A"
}, {
"name": "bbb",
"level": "B"
}, {
"name": "ccc",
"level": "C"
}];
display();
function display() {
var table = document.getElementById("mytable");
var length = myArray.length;
for (var i = 0; i < length; i++) {
var row = table.insertRow(i + 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = myArray[i].name;
cell2.innerHTML = myArray[i].level;
} //end for
} //end display
的HTML:
<html>
<head>
<meta charset="UTF-8">
<script src="myscript.js"></script>
</head>
<body id="body">
<div id="wrapper">
<table align='center' cellspacing=1 cellpadding=1 id="mytable" border=1>
<tr>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
<tr>
<td><input type="text" id="text"></td>
<td>
<select name="levels" id="levels">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" id="add-button" value="Add"></td>
</tr>
</table>
</div>
</body>
</html>
问题:
当我在Chrome中打开该页面,我没有看到数组元素添加到表中,我得到这个错误:
get-text.js:17 Uncaught TypeError: Cannot read property 'insertRow' of null at display (myscript.js:17) at myscript.js.js:9
你目前的代码似乎工作正常。发生了什么,你期望发生什么? – larz
谢谢你告诉我们你的问题。这导致我认为'table'为空,这可能是因为你的JavaScript在DOM被加载之前被调用。如果是这种情况,请考虑在调用JS之前等待文档准备就绪。 – larz
@larz它正在工作。谢谢。 – user7945230