簡體   English   中英

如何使用JavaScript在其他2個列之間的表中添加列

[英]How to add columns to a table between 2 other columns with JavaScript

我有一個由用戶動態創建的表,可以有1000多個行。 通過單擊按鈕,用戶可以操縱表格,但是當用戶單擊按鈕時,我無法弄清楚如何在整個表格中添加列,以及如何使其出現在我想要的位置。 這是一些示例代碼。

 table td, table th{ border: 2px solid #0f0f0f; text-align:center; } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <table> <tbody id = "tableBody"> <tr class = "date" ><td colspan = "2">DATE</td></tr> <tr class = "alt" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt2" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt2" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "date" ><td colspan = "2">DATE</td></tr> <tr class = "alt" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt2" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt2" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "date" ><td colspan = "2">DATE</td></tr> <tr class = "alt" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt2" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt" ><td>Cell1</td><td>Cell2</td></tr> <tr class = "alt2" ><td>Cell1</td><td>Cell2</td></tr> </tbody> </table> </body> </html> 

如何在整個表格的cell1和cell2之間添加一列? 我考慮過創建一個函數,該函數獲取所有行的innerHTML,然后為另一列添加代碼-但這不會在兩列之間添加單元格。

我只是嘗試創建Javascript函數以在column1和column2之間添加新列。 此功能應附加在按鈕的onclick事件上。 這是Javascript片段供您參考:

   <script language="javascript" type="text/javascript">
        function insertColumn(position) {
            //Find the tr by class name: alt
            var row = document.getElementsByClassName('alt');
            for (index = 0; index < row.length; index++) {
                var cell = row[index].insertCell(position);
                cell.innerHTML = "New Column";
            }

            //Find the tr by class name: alt2. I would suggest you to use same class for the TR, where we are adding a new column
            var row = document.getElementsByClassName('alt2');
            for (index = 0; index < row.length; index++) {
                var cell = row[index].insertCell(position);
                cell.innerHTML = "New Column";

            }


        }
    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM