【问题标题】:HTML table creation with DOM使用 DOM 创建 HTML 表
【发布时间】:2016-04-29 14:30:02
【问题描述】:

谁能告诉我如何用 DOM html javascript 创建这个表。我试图创建一个按 ID 查找元素并添加到现有 <table class="overflow-y"></table> 标记的函数。但是我找不到查看我生成的 html 代码的方法,也不知道我哪里出错了。

<table id="mytable" class="overflow-y">
  <thead>
    <tr>
      <th>corner</th><th>header1</th><th>header2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>row1</th><td>1-1</td><td>1-2</td>
    </tr><tr>
      <th>row2</th><td>2-1</td><td>2-2</td>
    </tr><tr>
      <th>row3</th><td>3-1</td><td>3-2</td><
    </tr><tr>
      <th>row4</th><td>4-1</td><td>4-2</td>
    </tr><tr>
      <th>row25</th><td>5-1</td><td>5-2</td
    </tr>
  </tbody>
</table>

【问题讨论】:

标签: javascript html dom dynamic html-table


【解决方案1】:

我在Fiddle 中做的例子怎么样。

考虑这个 HTML 结构

<table id="myTable" class="table">
   <tbody></tbody>
</table>
<hr>
<button class="button" id="addRow">Row +</button>
<button class="button" id="addColumn">Column + </button>

在 html 中,您有添加列和行的按钮。

通过以下 jquery 函数,您可以控制生成行和列的方式。

(function($){
    $(document).ready(function(){
    var myTable = $('#myTable');
    addRows(myTable);
    addColumns(myTable);

  });

  function addRows(table){
    $('#addRow').click(function(){
        var lastRow = $('#myTable > tbody > tr:last-child'); //fetch last row so you can copy it. You will need to find a way to copy only the structure.


      if(lastRow.length > 0){
        table.append(lastRow.clone()); //Append a copy of the last row to the table
      }
      else{
        table.append($('<tr></tr>')); //create an empty row
      }
    });
  }

  function addColumns(table){
    $('#addColumn').click(function(){
            var rows = $('#myTable > tbody > tr'); //Get all rows
        rows.append($('<td>Column</td>')); //Append a td to all rows in the body
    });
  }
})(jQuery);

在您的最终代码中,您需要:

  • 控制列数,以免得到奇怪的表格。
  • 添加一个输入,以便您可以将 th 添加到一个

希望它可以帮助您入门。

【讨论】:

  • 这看起来很不错,我从未使用过 JQuery,但我将开始学习一些教程然后编辑您的代码。我想我应该为函数添加行数/列数的参数,以便在加载 html 页面时可以构建表格。非常感谢。
猜你喜欢
  • 2011-07-12
  • 2011-09-30
  • 2012-01-08
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多