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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14964253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:28:43  来源:igfitidea点击:

How to dynamically add a new column to an HTML table

javascriptjqueryhtml

提问by Anthony

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 Columnbutton 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 trin the table except the first row since that is the column names

所以当用户点击按钮时,列名应该是文本框中的值,行级别应该是复选框。所以基本上新列应该附加到tr表中除了第一行之外的所有内容,因为那是列名

采纳答案by GNi33

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在最后将- 值替换为该值。

回答by GNi33

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">'))});
}
});

回答by aloisdg moving to codidact.com

Modern pure JavaScript solution:

现代纯 JavaScript 解决方案:

function addColumn() {
    [...document.querySelectorAll('#table tr')].forEach((row, i) => {
        let input = document.createElement("input")
        input.setAttribute('type', 'text')
        let 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 thinstead of td. Each new cell contains a input. Feel free to change this to suit your need.

第一行将包含一个th而不是td。每个新单元格都包含一个input. 随意更改它以满足您的需要。

回答by Praveen Kumar Purushothaman

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" />. And it is better to

但是您需要使用文本和其他内容更改第一行的值以包含<input type="checkbox" />. 而且最好

回答by Praveen Kumar Purushothaman

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>");       
            })
     });      
 });