使用 JavaScript 擷取 table 行號和列號(附原始碼)

來源:互聯網
上載者:User

怎樣擷取預定義的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));

                                   }

                            }

                     }

              }

       }

(註:關鍵代碼已經加黑)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.