在實際開發中,我們經常需要把某個表格裡的數據動態地追加到另一個表格中。本文就通過一個完整的例子,帶你一步步實現這個功能。
首先,我們準備一個頁面,裡面放置兩個表格:上面一個表格有數據,下面一個表格只有表頭。
<body>
<form id="form1" runat="server">
<div>
<table border='1px' width="500px" id="tables">
<tr>
<td>1</td><td><input type="text" value="20" style="width:50px" /><input type="text" value="200" style="width:50px" /></td><td>我是中國人</td><td>好好學習</td><td><input type="button" id="but" value="新增" onclick="butd(this);" /></td>
</tr>
<tr>
<td>2</td><td><input type="text" value="30" style="width:50px" /><input type="text" value="300" style="width:50px" /></td><td>我是中國人</td><td>好好學習</td><td><input type="button" id="Button1" value="新增" onclick="butd(this);" /></td>
</tr>
<tr>
<td>3</td><td><input type="text" value="40" style="width:50px" /><input type="text" value="400" style="width:50px"/></td><td>我是中國人</td><td>好好學習</td><td><input type="button" id="Button2" value="新增" onclick="butd(this);" /></td>
</tr>
<tr>
<td>4</td><td><input type="text" value="50" style="width:50px" /><input type="text" value="500" style="width:50px" /></td><td>我是中國人</td><td>好好學習</td><td><input type="button" id="Button3" value="新增" onclick="butd(this);" /></td>
</tr>
<tr>
<td>5</td><td><input type="text" value="60" style="width:50px" /><input type="text" value="600" style="width:50px" /></td><td>我是中國人</td><td>好好學習</td><td><input type="button" id="Button4" value="新增" onclick="butd(this);" /></td>
</tr>
</table>
</div>
<div>
<table border='1px' width="500px" id="table2">
<tr><td>ID</td><td>年齡</td><td>金錢</td><td>名字</td></tr>
</table>
</div>
</form>
</body>
接下來,當用戶點擊「新增」按鈕時,我們把當前行所對應的數據動態地追加到下方的表格中。JavaScript 代碼如下:
<script type="text/javascript">
function butd(rows) {
var rows = rows.parentNode.parentNode.rowIndex; //找到當前選中的行
var mytable = document.getElementById('tables'); //找到當前的 table
var Romm_price = mytable.rows[rows].cells[0].innerText; //第一列的值
var room_rows = mytable.rows[rows].cells[1].children[0].value; //第二列第一個文本框的值
var room_rows2 = mytable.rows[rows].cells[1].children[1].value; //第二列第二個文本框的值
var room_rows3 = mytable.rows[rows].cells[2].innerText; //第三列的值
//找到 table2,並新增一行
var x = document.getElementById('table2').insertRow();
x.align = "center"; //設置行樣式
var Romm_typename = x.insertCell(0);
var txtDate = x.insertCell(1);
var Guest_Type_ID = x.insertCell(2);
var room_row = x.insertCell(3);
Romm_typename.innerHTML = Romm_price;
txtDate.innerHTML = room_rows;
Guest_Type_ID.innerHTML = room_rows2;
room_row.innerHTML = room_rows3;
}
</script>
這段代碼中最關鍵的兩點是:一是如何準確獲取用戶當前點擊的是哪一行,二是如何手動把當前行的數據添加到目標表格中。掌握了 rowIndex 定位行、以及 insertRow() 與 insertCell() 動態構建行的技巧,你就能輕鬆應對各種類似的表格操作需求。