標籤:index ram doc insert table time log 方法 cell
CreateTime--2017年4月15日08:09:43Author:Marydonjs-動態插入、刪除table行用到table的insertRow()和deleteRow()方法
<input id = "userName" type="button" value="增加行" onclick="insertRow();"/><input id = "userName" type="button" value="刪除行1" onclick="delRow();"/><input id = "userName" type="button" value="刪除行3" onclick="delRow3();"/><table id="testTab" border="1" style="border-collapse: collapse;" width="99%"> <tr> <td>a1</td> <td>a2</td> <td>a3</td> </tr></table>
1.動態插入行
/** * 在最後一個tr後插入行 */function insertRow () { var table = document.getElementById("testTab"); var newRow = table.insertRow(-1);//新增行(最後一行) var newCell1 = newRow.insertCell(0);//第一列 newCell1.innerHTML = "b1"; var newCell2 = newRow.insertCell(1);//第二個儲存格 newCell2.innerHTML = "b2"; var newCell3 = newRow.insertCell(2);//第三個儲存格 newCell3.innerHTML = "b3"; newRow.insertCell(3).innerHTML = "<input type=‘button‘ value=‘刪除行2‘ onclick=‘delRow2(this);‘/>"}2.刪除行
/** * 刪除最後一行tr */function delRow () { var table = document.getElementById("testTab"); var lastRowIndex = table.rows.length - 1;//最後一個tr的索引值 table.deleteRow(lastRowIndex); }
/** * 刪除指定行 * @param {Object} rowIndex * 行索引 */function delRow2 (inputObj) { var trObj = inputObj.parentNode.parentNode; var rowIndex = trObj.rowIndex; var table = trObj.parentNode; table.deleteRow(rowIndex);}
/** * 有參無參都可以 * @param {Object} obj */function delRow3 (obj) { var tableObj = null; var rowIndex = -1; if (obj) { tableObj = obj.parentNode.parentNode.parentNode; rowIndex = obj.parentNode.parentNode.rowIndex; } else{ tableObj = document.getElementById("testTab"); rowIndex = tableObj.rows.length - 1; } tableObj.deleteRow(rowIndex); }
js-動態為table插入、刪除行