使用 JavaScript 獲取 table 行號和列號

iDotNetSpace發表於2008-09-27

怎樣獲取預定義的table的行號和列號呢?很簡單,只需要瞭解 table 的幾個屬性值用法即可。Table的總行數可以通過標記“tr 得到,但是table的列數卻不能直接獲取,它需要藉助 rows 通過標記“th 和“td”得到。

為了更直觀,下面以示例來說明如何得到行號和列號。點選 Id 'MyTable' 的表格的任意單元時,返回該單元的行號和列號!示例程式碼如下:

       function  getRowAndColumn()

       {

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

              var rows = document.getElementById('MyTable').getElementsByTagName('tr');

              var cols;

              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));

                                   }

                            }

                     }

              }

       }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-465893/,如需轉載,請註明出處,否則將追究法律責任。

相關文章