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

时间:2015-01-17 19:59:16

标签: 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>
&#13;
&#13;
&#13;

如何在整个表格中在cell1和cell2之间添加一列?我想过创建一个获取所有行的innerHTML的函数,然后为另一列添加代码 - 但是这不会在两列之间添加一个单元格

1 个答案:

答案 0 :(得分:0)

我刚尝试创建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>