Javascript实现动态增加、删除表格域

<html>
<head>
<title> Dynamic add or delete rows of a table </TITLE>

<script language = "javascript">

    function getTable() {
        return document.getElementById("testid");
    }

    function addRow() {
        var cell0_html = '<a href=# οnclick=/"deleteRow(this)/">delete</a>';
        var cell1_html = '<input type=/"text/">';

        var tbl = getTable();
        var row;
        var cell;

        // add new row after the last row -- TR
        row = tbl.insertRow(tbl.rows.length);

        // create a cell for the new row  -- TD
        cell = tbl.rows.item(tbl.rows.length - 1).insertCell(0);
        cell.innerHTML = cell0_html;

        cell = tbl.rows.item(tbl.rows.length - 1).insertCell(1);
        cell.innerHTML = cell1_html;

        var rowIdx = tbl.rows.length -1 ; // first row -- 0
        // store the row index into the related row
     //     row's first cell's first child -- refer to "<a href=#"
        tbl.rows.item(tbl.rows.length-1).cells.item(0).children.item(0).text = rowIdx;
     alert("rowIdx="+rowIdx);
    }

    function deleteRow(x) {
        var tbl = getTable();
     // delete the row by row index
        tbl.deleteRow(x.text.valueOf());
     // refresh the row index
        for (var j = 1; j < tbl.rows.length; j++)
            tbl.rows.item(j).cells.item(0).children.item(0).text=j;
    }

    function refreshIndex() {
        // refresh the row index
        for (var j = 1; j < tbl.rows.length; j++)
            tbl.rows.item(j).cells.item(0).children.item(0).text=j;
    }


</script>
</head>
<body>
<input type="button" value="add" οnclick="addRow()">

<table width="100%" id="testid" border=1>
    <tr>
     <td>H-1</td>
     <td>H-2</td>
 </tr>
</table>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值