动态添加行到具有动态接收列数的表

时间:2013-12-02 12:24:42

标签: javascript

当用户发出命令将它们添加到打印行的末尾时,我需要动态地向表中添加行。但是,对于特定行,必须添加的列数因表而异。

应该添加的列数是动态地到达每个表。因此,打印的列数必须随时变化。这是我使用的代码。

 $(document).ready(function(){



 $("#anc_add").click(function(){ //This is the ID of the button where user gives the command to add rows.


 var Total=$("#NumberOfColumns").val(); //This is the number of input boxes I must add to that row......


  $('#tbl1 tr').last().after(

  '<tr><td>Static Content ['+cnt+']</td><td><input type="text" name="txtbx'+cnt+'"  value="'+cnt+'">;

  ); // I need to print the given(Total) number of input boxes instead of printing textboxes like this.

   cnt++;
  });



 });

有人可以建议我这样做的方法。非常感谢你。

3 个答案:

答案 0 :(得分:1)

这将循环您要添加的输入总数。

$("#anc_add").click(function(){ //This is the ID of the button where user gives the command to add rows.


 var Total=$("#NumberOfColumns").val();

 var rowElem = $('<tr>').append(
    $('<td>').html('Static Content ['+cnt+']')
 );

for(var i = 0; i < Total; i++) {
  rowElem.append(
     $('<td>').html('<input type="text" name="txtbx'+cnt+'"  value="'+cnt+'">')
  ) 
  cnt++;
}

  $('#tbl1 tr').last().after(
      rowElem
  );
  });



 });

答案 1 :(得分:0)

试试这个:

$('#my_table > tbody > tr').eq(i-1).after(html);

$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');

答案 2 :(得分:0)

建议:

// What you want your new rows to be filled with :

var defaultValues = {
    'col0' : 'val0',
    'col1' : 'val1',
    'col2' : 'val2'
};

// A "template", which could be inside the HTML, to keep the code clear, i.e
// out of loops and if possible out of JavaScript.

var rowTemplate =
    '<tr>' +
        '<td>{{col0}}</td>' +
        '<td>{{col1}}</td>' +
        '<td>{{col2}}</td>' +
    '</tr>';

var oldNbRows = ...,
    newNbRows = ...;

// Only select the table once, unless it is dynamically created / deleted.

var $table = $( '#myTable' );

// Add extra rows :

for( var i = 0, maxI = newNbRows - oldNbRows; i < maxI; ++i )
{
    var html = rowTemplate;

    for( var key in defaultValues )
    {
        html.replace( '{{' + key + '}}', defaultValues[key] );
    }

    $table.children( 'tr' ).last().after( html );
}