Javascript 用DOM创建HTML表

Javascript 用DOM创建HTML表,javascript,html,dom,dynamic,html-table,Javascript,Html,Dom,Dynamic,Html Table,有人能告诉我如何用DOM html javascript创建这个表吗。我尝试创建一个函数,通过ID查找元素并添加到现有的标记中。但是,我找不到查看生成的html代码的方法,也不知道哪里出错了 <table id="mytable" class="overflow-y"> <thead> <tr> <th>corner</th><th>header1</th><th>header

有人能告诉我如何用DOM html javascript创建这个表吗。我尝试创建一个函数,通过ID查找元素并添加到现有的
标记中。但是,我找不到查看生成的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>

角头1头2
第11-11-2行
第22-12-2行
第33-13-2行<
第44-14-2行

第255-15-2行我在本文中所做的示例如何

考虑一下这个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);
(函数($){
$(文档).ready(函数(){
var myTable=$(“#myTable”);
addRows(myTable);
addColumns(myTable);
});
函数addRows(表){
$('#addRow')。单击(函数(){
var lastRow=$('#myTable>tbody>tr:last child');//获取最后一行以便可以复制它。您需要找到一种只复制结构的方法。
如果(lastRow.length>0){
table.append(lastRow.clone());//将最后一行的副本追加到表中
}
否则{
table.append($('');//创建一个空行
}
});
}
函数addColumns(表){
$('#addColumn')。单击(函数(){
var rows=$('#myTable>tbody>tr');//获取所有行
rows.append($('Column');//将td附加到正文中的所有行
});
}
})(jQuery);
在最终代码中,您需要:

  • 控制列的数量,这样你就不会得到一个奇怪的表
  • 添加一个输入,以便可以将th添加到

希望它能帮助您入门。

?这就是您要找的吗?动态行几乎就是我要找的@OmarYafer,但我也有动态的列数。这看起来很不错,我从未使用过JQuery,但我将开始学习一些教程,然后编辑您的代码。我想我应该为函数添加行数/列数的参数,以便在加载html页面时可以构建表。非常感谢。