在JavaScript中使用HTML表格时这是正确的方法吗?
我必须创建动态的html表,但我不知道。
请告诉我一个好主意!
<tbody>
<tr>
<td>row1</td>
<td>val1</td>
<td>val2</td>
<td>val3</td>
<td>val4</td>
</tr>
<tr>
<td>row2</td>
<td>val1</td>
<td>val2</td>
<td>val3</td>
<td>val4</td>
</tr>
...
</tbody>
var tableArr = {
row1: [],
row2: [],
};
tableArr.row1.push('1');
tableArr.row1.push('2');
tableArr.row1.push('3');
tableArr.row1.push('4');
tableArr.row2.push('1');
tableArr.row2.push('2');
tableArr.row2.push('3');
tableArr.row2.push('4');
for (var row in tableArr) {
console.log(row);
for (var i=0; i<tableArr[row].length; i++) {
console.log(tableArr[row][i]);
}
}
请告诉我一个好主意! :d
答案 0 :(得分:1)
您可以使用javascript方法创建表格和行等。
var tableRef = document.createElement('table');
for (var i = 0; i <= 5; i++) {
var newRow = tableRef.insertRow(i);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode('New top row #' + i);
newCell.appendChild(newText);
}
document.body.appendChild(tableRef);
&#13;
答案 1 :(得分:0)
您需要访问DOM并修改HTMLTableElement才能从JavaScript中查找HTML表格。
您的初始HTML代码:
<table id="myTable">
</table>
您的JavaScript代码:
// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
JavaScript更新后的HTML代码:
<table id="myTable">
<tr>
<td>NEW CELL1</td>
<td>NEW CELL2</td>
</tr>
</table>