简体   繁体   English

如何向 HTML 表格动态添加新列

[英]How to dynamically add a new column to an HTML table

I have a table to which I am currently dynamically adding rows: http://jsfiddle.net/fmuW6/5/我有一个表,我目前正在向其中动态添加行: http : //jsfiddle.net/fmuW6/5/

Now I'd like to add a new column to the table as well with a click of a button.现在,我还想通过单击按钮向表格中添加一个新列。 The user will enter the column header in a textbox.用户将在文本框中输入列标题。

How can I achieve this?我怎样才能做到这一点? If the user adds 4 rows, the Add a new Column button should take care of all the existing rows (adding checkbox in each one).如果用户添加 4 行,“ Add a new Column按钮应处理所有现有行(在每一行中添加复选框)。

update更新

I'm looking to add column name and checkbox at row level.我希望在行级别添加列名和复选框。

so I've added the text box in which the user will input the column name: http://jsfiddle.net/fmuW6/10/所以我添加了用户将在其中输入列名的文本框: http : //jsfiddle.net/fmuW6/10/

<input type=text placeholder='columnname'/>
<button type="button" id="btnAddCol">Add new column</button></br></br>

so then when user clicks the button the columnname should be the value in the textbox and at the row level should be checkboxes.所以当用户单击按钮时,列名应该是文本框中的值,而行级别应该是复选框。 So basically the new column should be appended to all tr in the table except the first row since that is the column names所以基本上新列应该附加到表中除了第一行之外的所有tr ,因为那是列名

I updated your fiddle with a small example how you could do that.我用一个小例子更新了你的小提琴,你如何做到这一点。

jsFiddle - Link jsFiddle - 链接

var myform = $('#myform'),
    iter = 0;

$('#btnAddCol').click(function () {
     myform.find('tr').each(function(){
         var trow = $(this);
         if(trow.index() === 0){
             trow.append('<td>Col+'iter+'</td>');
         }else{
             trow.append('<td><input type="checkbox" name="cb'+iter+'"/></td>');
         }
     });
     iter += 1;
});

This would add a new column to every row, including an count-variable that gets applied to the first row as name and to the name-attribute of the checkboxes on the following rows.这将向每一行添加一个新列,包括一个计数变量,该变量作为名称应用于第一行以及随后行中复选框的名称属性。

Consider using th - elements for the table header, that way you wouldn't need the index-check i'm making and it would be more semantically correct.考虑将th - 元素用于表头,这样您就不需要我正在做的索引检查,而且在语义上会更正确。

I left out the part where the user would put in a name for the column, but as you see, you could just replace the iter - value with that in the end.我省略了用户为列输入名称的部分,但如您所见,您可以最终将iter - 值替换为该值。

Modern pure JavaScript solution:现代纯 JavaScript 解决方案:

 function addColumn() { [...document.querySelectorAll('#table tr')].forEach((row, i) => { const input = document.createElement("input") input.setAttribute('type', 'text') const cell = document.createElement(i ? "td" : "th") cell.appendChild(input) row.appendChild(cell) }); } document.querySelector('button').onclick = addColumn
 <table id="table"> <tr><th><input type="text" value="test 1" /><th/></tr> <tr><td><input type="text" value="test 2" /><td/></tr> </table> <button type="button">add column</button>

First row will contain a th instead of td .第一行将包含th而不是td Each new cell contains a input .每个新单元格都包含一个input Feel free to change this to suit your need.随意更改它以满足您的需要。

The answer works, but still here is an alternative way where we use thead and tbody !答案有效,但这里仍然是我们使用 thead 和 tbody 的另一种方式!

JS

$('#irow').click(function(){
if($('#row').val()){
    $('#mtable tbody').append($("#mtable tbody tr:last").clone());
    $('#mtable tbody tr:last :checkbox').attr('checked',false);
    $('#mtable tbody tr:last td:first').html($('#row').val());
}
});
$('#icol').click(function(){
if($('#col').val()){
    $('#mtable tr').append($("<td>"));
    $('#mtable thead tr>td:last').html($('#col').val());
    $('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="checkbox">'))});
}
});

Use this code for adding new column:使用此代码添加新列:

$('#btnAddCol').click(function () {
    $("tr").append("<td>New Column</td>");
});

But you need to change the value for the first row with a text and others to include a <input type="checkbox" /> .但是您需要使用文本和其他内容更改第一行的值以包含<input type="checkbox" /> And it is better to而且最好

Check it out jsFiddle ............................. http://jsfiddle.net/fmuW6/8/看看 jsFiddle ..................... http://jsfiddle.net/fmuW6/8/

 $(document).ready(function () {
        $('#btnAdd').click(function () {
              var count = 3, first_row = $('#Row2');
                while(count-- > 0)                    first_row.clone().appendTo('#blacklistgrid');
     });   

        $('#btnAddCol').click(function () {
            $("#blacklistgrid tr").each(function(){
               $(this).append("<td>test</td>");       
            })
     });      
 });

Using a table of 4 columns:使用 4 列的表格:

在此处输入图片说明

I can add values dinamically like this:我可以像这样动态地添加值:

 var TableId = "table_" + id; 

 var table = $("#" + TableId );

 table.find("tbody tr").remove();
                                            
 table.append("<tr><td>" + "1" + "</td><td>" + "lorem"  + "</td><td>" + "ipsum" + "</td><td>" + "dolor" + "</td></tr>");

and the final result will be:最终结果将是:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM