【问题标题】:How to add columns to a table between 2 other columns with JavaScript如何使用 JavaScript 将列添加到其他 2 列之间的表中
【发布时间】:2015-01-17 19:59:16
【问题描述】:

我有一个由用户动态创建的表,可以有超过 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


    【解决方案1】:

    我刚刚尝试创建 Javascript 函数以在 column1 和 column2 之间添加一个新列。此功能应附加在按钮的 onclick 事件上。 这是 Javascript sn-p 供您参考:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 2019-02-03
      • 2021-08-12
      • 1970-01-01
      • 2014-11-05
      • 2015-04-25
      相关资源
      最近更新 更多