我試圖用javascript將行插入到html表中。我創建了表格,只需點擊一個按鈕即可成功添加行。但是,我希望能夠在加載時使用來自多個數組的元素填充行。該按鈕只是爲了確保行被添加。使用javascript在HTML表格中添加行
<html>
<input type="button" value="Add row" onclick="javascript:appendRow()" class="append_row"/>
<br/><br/></p>
<table id="my_table" align="center" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
</table>
<p></center></p>
<script type="text/javascript" language="javascript">
function appendRow(){
var names = ["Paul", "Mike", "Linda"];
var ages = ["16", "23", "44"];
var male_female = ["M", "M", "F"];
var tbl = document.getElementById('my_table'); // table reference
// append table row
var row = tbl.insertRow(tbl.rows.length);
// insert table cells to the new row
var row = tbl.insertRow();
for(var i=0;i<tbl.rows[0].cells.length;i++)
createCell(row.insertCell(i), i, 'row');
}
function createCell(cell, text, style){
var div = document.createElement('div'); // create DIV element
var txt = document.createTextNode(text); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('class', style); // set DIV class attribute
div.setAttribute('className', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
</script>
<style>
.row{background-color:#FFD6D6;width:43px;margin:3px;}
.col{background-color:#D6FFD6;width:43px;margin:3px;}
table#my_table{border-collapse:collapse;}
table#my_table td{width:50px;height:27px;border:1px solid #D3D3D3;font- size:10pt;text-align:center;padding:0;}
.append_row{background-color:#FFD6D6;border:1px #ccc solid;}
.append_column{background-color:#D6FFD6;border:1px #ccc solid;}
.delete{background-color:#eee;border:1px #ccc solid;}
</style>
</html>
重的'setAttribute'調用和IE的黑客:在HTML文檔中不使用'getAttribute' /'setAttribute',因爲這個原因。更好地堅持像DOM.className = style'這樣的DOM Level 1 HTML屬性。 – bobince 2010-09-17 00:22:24