我用 HTML 創建了一個表,我需要用來自 JS 的陣列加入該表:
var array = [
["A4", "Audi", "2015", "1234"],
["A3", "Audi", "2011", "1542"],
["335i", "BMW", "2012", "9874"],
["440d", "BMW", "2015", "1975"],
["Civic", "Honda", "2002", "6574"],
]
console.log(array)
table = document.getElementById("myTable");
for (var i = 0; i < array.length; i ) {
// create a new row
var newRow = table.insertRow(table.length);
for (var j = 0; j < array[i].length; j ) {
// create a new cell
var cell = newRow.insertCell(j);
// add value to the cell
cell.innerHTML = array[i][j];
}
}
<table id="myTable">
<caption id=a><b>Automobiliai</caption></b>
<tr>
<th>Modelis</th>
<th>Gamintojas</th>
<th>Metai</th>
<th>Variklio Numeris</th>
</tr>
</table>
但是我在控制臺中收到錯誤訊息:“未捕獲的型別錯誤:無法讀取 null 的屬性(讀取 'insertRow')” 有什么問題?
uj5u.com熱心網友回復:
您可以通過遍歷國家/地區串列并創建一個 HTML 字串來完成此操作。然后您可以使用類或 id 選擇器將其放入 tbody 中。這是一個例子
var country = ["Norway", "Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm" , "Copenhagen"]
var bodyString = '';
$.each(country, function(index, ctry) {
bodyString = ('<tr><td>' ctry '</td><td>' capital[index] '</td></tr>');
});
$('.countriesTable tbody').html(bodyString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table class="countriesTable">
<thead>
<tr><th>Country</th><th>Capital</th>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
uj5u.com熱心網友回復:
看起來您的代碼有效。這是另一種方法,使用
我想,我發現了你的問題,實際上你的腳本是在回圈元素之前加載的
uj5u.com熱心網友回復:
當我將您的代碼添加到jsfiddle 時,它起作用了
那么問題究竟出在哪里呢?
也許你在你的表加載之前加載你的 JS,這可以解釋為什么它在 JS fiddle 上作業,因為它在正確的時間加載 JS。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/354014.html
標籤:javascript html
