javascript表の行を動的に挿入し、削除します.

2057 ワード

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>          </title>
    <style>
        h2,h5,#tooltipMsg,p {
            white-space: nowrap;
        }
        td {
            border: 1px solid #ccc;
            height: 50px;
            text-align: center;
            font-size: 10pt;
            padding: 2px;
        }
    </style>
</head>
<body>
    <table id="tableAct" border="1" width="500">
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
    </table>
<input type="button" id="deleteRow" value="     " />
<input type="button" id="addRow" value="    " />
<script>
    window.onload=function(){
        trAct=function(table,num,tr){
            if(!tr){ //  tr     ,      
                var _num=table.rows[num];
                if(_num){ //           ,   ,  true
                    table.deleteRow(_num);//js        
                    return true;
                }
                else {
                    return false;//          ,     ,  false;
                }
            }
            else {
                var r=table.insertRow(num), //           
                        i= 0,
                        l=tr.length;//        
                for(;i<l;i++){ //       
                    r.insertCell(i).innerHTML=tr[i];//        
                }
                return true;//       true;
            }
        }
        /*          */
        var _tableAct=document.getElementById("tableAct");
        document.getElementById("deleteRow").onclick=function(){ //     
            trAct(_tableAct,0);
        }
        document.getElementById("addRow").onclick=function(){
            trAct(_tableAct,0,["     1","     2"]);
        }
    }
</script>
</body>
</html>