动态地向jQuery添加新表行

时间:2015-08-01 09:02:55

标签: jquery

我正在尝试使用jQuery(动态)向表中添加新行。以下是我正在使用的代码。

它正在创建新行,但不会创建列。有谁知道为什么?

$.each(json['rows'], function(k, v) 
{
    // enable export buttons
    $('.btn-export').show();

    // create new row
    var newRow = $('table tbody tr:last').after('<tr></tr>');

    $('table thead tr th').each(function(index)
    {
        var th      = $(this).text();
        var field   = $(this).attr('data-field');

        newRow.append($('<td data-th="' + th + '">').text('test'))
    });

    newRow.effect("highlight", {color: '#CCB4A5'}, 1000);
});

json['rows']对象如下所示:

Object { location_name: "Barnes", places: 4, voucher155: "129.17", paidbycard: "387.50" }

1 个答案:

答案 0 :(得分:2)

<强> 2。更新

var json={rows:[{location_name: "Barnes", places: 4, voucher155: "129.17", paidbycard: "387.50" },
         {location_name: "High Whycombe", places: 2, voucher155: "239.23", paidbycard: "225.50" }]};

$('.addrow').click(function(){
     // enable export buttons
     $('.btn-export').show();
     $.each(json.rows, function(i,row){
       var str='<tr>';
       // to just collect "any" properties into the current tr do:
   //  for (col in row) str+='<td>'+row[col]+'</td>';
       
       // if you want to make sure to get the "right" columns, do
       str+='<td>'+row['location_name']+'</td><td>'
                  +row.places+'</td><td>'
                  +row['voucher155']+'</td><td>'
                  +row.paidbycard+'</td>';
       str+='</tr>';
 
       $(str).appendTo('table').effect("highlight", {color: '#CCB4A5'}, 1000);
     });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<button class="addrow">add rows</button><br>
<table><tr><th>location name</th><th>places</th><th>voucher155</th><th>paidbycard</th></tr></table>

为了更清楚地说明我的假设,这次我在你的json.rows“对象数组中添加了第二行”。

第3。更新

使用appendTo()代替append(),您可以轻松地将所选的effect()应用于新填充的表格行。