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

(转http://blog.csdn.net/net511/article/details/5311774

增加删除: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 { 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].onclick=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"  onclick="addTab()"/>
        <input id="Button2" type="button" value="删除row"  onclick="delTab()"/>
        <input id="Button3" type="button" value="计算row cell"  onclick="sumTab()"/>
    </div>
    </form>
</body>
</html>

 

posted @ 2015-04-15 18:16  sqchi1991  阅读(9)  评论(0)    收藏  举报