Append columns to an HTML table offsetting from ri

2019-09-04 09:49发布

问题:

How can I count the number of columns in the first row of a table, subtract by one and then insert a column at that location into my table? I would like the first row of that column to be different than the rest of them.

Here is a basic fiddle that inserts columns into a table at a fixed location.

This topic discusses inserting new columns. Problem is that it uses a fixed, from the left, position to insert the column. It also does not change the top column.

Here is my sample code adapted from that post:

$(document).ready(function(){
   $('#AddOT').click(function(){
      $('#Table1').find('tr').each(function(){
          $(this).find('td').eq(0).after('<td>cell 1a</td>');
      });
    });
 });

This topic discusses determining the number of columns in "tables". The sample does not seem to work because placing multiple tables in the HTML creates a problem:

    $(function() {
        var colCount = 0;
        $('tr:nth-child(1) td').each(function () {
            if ($(this).attr('colspan')) {
                colCount += +$(this).attr('colspan');
            } else {
                colCount++;
            }
        });
    });

There is a jsfiddle to go along with the counting of the columns.

EDIT: Problem is solved and I was able to make a revised fiddle that places different content into different rows according to the row index value.

This will be very useful as I have different classes of text input boxes on different rows and I sum them according to class. I can now dynamically add new columns to all the rows but still keep unique classes of cells in each row. Awesome!

回答1:

I'm not sure if I understand your requirement correctly. Take a look at the demo

$(document).ready(function(){
            $('#AddOT').click(function(){
                   var count = countColumn();
                   var insertedPosition = count-2;
                    $('#Table1').find('tr').each(function(index){
                        if (index == 0){
                            var colspan = $(this).attr('colspan') || "1";
$(this).attr('colspan',parseInt(colspan)+1);                            
                        }
                        else
                        {
                        $(this).find('td').eq(insertedPosition ).after('<td>cell 1a</td>');
                        }
                    });

            });
});

function countColumn() {
    var colCount = 0;
    $('tr:nth-child(1) td').each(function () {
        if ($(this).attr('colspan')) {
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
    return colCount;
}