当前位置导航:炫浪网>>网络学院>>网页制作>>JavaScript教程

使用 JavaScript 获取 table 行号和列号

怎样获取预定义的table的行号和列号呢?很简单,只需要了解table的几个属性值用法即可。Table的总行数可以通过标记“tr”得到,但是table的列数却不能直接获取,它需要借助rows通过标记“th”和“td”得到。

为了更直观,下面以示例来说明如何得到行号和列号。点击Id为'MyTable'的表格的任意单元时,返回该单元的行号和列号!示例代码如下:

      function getRowAndColumn()

      {

              if(!document.getElementsByTagName || !document.createTextNode)return;

             varrows=document.getElementById('MyTable').getElementsByTagName('tr');

             varcols;

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

             {

                    rows[i].onclick=function()

                    {

                           alert("行:"+eval(this.rowIndex + 1));

                    }

                     if(i=0)

                    {

                           colsTH =rows[i].getElementsByTagName('th');

                            alert(colsTH.length);

                           for(k = 0; k< colsTH.length; k++)

                           {

                                  colsTH[k].onclick =function()

                                  {

                                         alert("列:"+eval(this.cellIndex +1));

                                  }

                            }

                     }

                     else

                     {

                           cols =rows[i].getElementsByTagName('td');

                           for(j = 0; j < cols.length; j++)

                           {

                                  cols[j].onclick =function()

                                  {

                                         alert("列:"+eval(this.cellIndex + 1));

                                  }

                            }

                     }

             }

       }

 

相关内容
赞助商链接