天天看點

javascript開發系列(table操作,table增加一行,删除一行,取行号,列号)

增加删除:insertRow,deleteRow, insertCell,deleteCell,

行号,列号:rowIndex ,cellIndex。

執行個體:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>無标題頁</title>

    <style  type="text/css">

        table { background-color:red; border:solid 1px red}

         td { background-color:#ffffff; border:solid 1px red}

    </style>

    <script type="text/javascript">

        function addTab()

        {

        var tb=document.getElementById("tb");

        tb.insertRow(0);

        tb.rows[0].insertCell(0);

        tb.rows[0].cells[0].appendChild(document.createTextNode("Name"));

        tb.rows[0].insertCell(1)

        tb.rows[0].cells[1].appendChild(document.createElement("input"))

        }

        function delTab()

        {

         var tb=document.getElementById("tb");

           (tb.rows.length<=0)?alert("請行增加相應的row"):tb.deleteRow(0);

        }

        function sumTab()

        {

         var tb=document.getElementById("tb");

         var smRow=tb.rows.length;

//         for(tr in tb.rows)

//         {

//           alert(tr.cells[1].firstChild.value());

//         }

      for(i=0;i<=tb.rows.length;i++)

       {

        alert(tb.rows[i].cells[1].firstChild.value);

        tb.rows[i].οnclick=function()

        {

          alert("我的行号是:"+this.rowIndex +"/n"+ "我的列号是:"+this.firstChild.cellIndex);//注意.tr隻有行号,td才有列号,是以第一個為this.rowIndex(tr) ,第二個為:this.firstChild.cellIndex(td)

        }

       }

        }

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <table id="tb"></table>

    <div>

        <input id="Button1" type="button" value="增加row"  οnclick="addTab()"/>

        <input id="Button2" type="button" value="删除row"  οnclick="delTab()"/>

        <input id="Button3" type="button" value="計算row cell"  οnclick="sumTab()"/>

    </div>

    </form>

</body>

</html>

繼續閱讀