2010-09-17 93 views
1

我試圖用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> 
+1

重的'setAttribute'調用和IE的黑客:在HTML文檔中不使用'getAttribute' /'setAttribute',因爲這個原因。更好地堅持像DOM.className = style'這樣的DOM Level 1 HTML屬性。 – bobince 2010-09-17 00:22:24

回答

2

在你的循環,你可以試試:

var j = tbl.rows.length - 1; 
for (var i=0;i<tbl.rows[0].cells.length;i++) { 
    var cell_text = ''; 
    if (i == 0) { 
    cell_text = name[j]; 
    } else if (i == 1) { 
    cell_text = ages[j]; 
    } else if (i == 2) { 
    cell_text = male_female[j]; 
    } 
    createCell(row.insertCell(i), cell_text, 'row'); 

} 
+0

似乎大部分工作。它從數組的第二個元素開始,但確實將所有內容放在了需要的位置。謝謝您的幫助。有沒有一種方法可以根據數組中元素的數量或長度來創建許多行?我將使用這個與未知長度的數組,並需要它相應地填充。 – cameron213 2010-09-17 00:48:44

+0

我想你需要j = tbl.rows.length - 2來考慮標題行。您可以使用outer for循環:for(var j = 0; j MattSmith 2010-09-17 03:56:14

1

你忘了在HTML語法中的 「」 標籤。您可以在onLoad變量中調用函數,以便在加載頁面後調用它。

+0

是的,我現在忽略了這個代碼,直到我看到它的實際工作。我正在尋找將這些元素放入行中的代碼。 – cameron213 2010-09-17 00:30:13