js-動態為table插入、刪除行

來源:互聯網
上載者:User

標籤: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插入、刪除行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.