使用Jquery生成表

时间:2018-06-28 09:00:39

标签: javascript jquery

我正在尝试生成一个表,该表的左侧为表头,右侧为表数据。

   var displayRecords = [{
     customers_transaction_detail_id: 1,
     customer_id: 2
   }];
   
   $('#emp_body').html('');
    for (var i = 0; i < displayRecords.length; i++) {
        th = $('<th/>');
        tr = $('<tr>');
        var row1 = "<th>Customer ID</th> <td>" + displayRecords[i].customer_id + "</td></tr>";
        var row2 = "<th>Transaction ID</th> <td>" + displayRecords[i].customers_transaction_detail_id + "</td></tr>";
        $('#emp_body').append(row1,row2);
    }

我的table tbody的ID为#emp_body。上面的代码生成一个水平表,而不是垂直表。

2 个答案:

答案 0 :(得分:0)

尝试一下:

$('#emp_body').html('');
var content = '<table>';
for(i = 0; i < 3; i++){
    content += '<tr><td>' + 'Result ' +  i + '</td></tr>';
}
content += '</table>';

$('#emp_body').append(content);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="emp_body"></div>

您的代码:

var displayRecords = [{
  customers_transaction_detail_id: 1,
  customer_id: 2
 }];

$('#emp_body').html('');
for (var i = 0; i < displayRecords.length; i++) {
 var content = '<tr>';

 content += '<th>Customer ID</th>';
 content += '<td>' + displayRecords[i].customer_id + '</td></tr>';

 content += '<th>Transaction ID</th>';
 content += '<td>' + displayRecords[i].customers_transaction_detail_id + '</td>';

 content += '</tr>';
 $('#emp_body').append(content);
}

并确保您table<tbody id="emp_body">

答案 1 :(得分:0)

我希望这会对您有所帮助。您可以更新样式并指定类名称。 谢谢。

var displayRecords=[
   {customers_transaction_detail_id:1,
   customer_id:2
   }];
   
   $('#emp_body').html('');
    for (var i = 0; i < displayRecords.length; i++) {
        //tr = $('<tr/>');
        th = $('<th/>');
        tr = $('<tr>');
        //tr.append("<td>" + displayRecords[i].customer_id + "</td>");
        var header= "<tr><th>Header</th><th>Value</th></tr>"
        var row1 = "<tr><td class=\"header\">Customer ID</td> <td class=\"value\">" + displayRecords[i].customer_id + "</td></tr>";
        var row2 = "<tr><td class=\"header\">Transaction ID</td> <td class=\"value\">" + displayRecords[i].customers_transaction_detail_id + "</td></tr>";
        $('#emp_body').append(header,row1,row2);
    }
th{
    padding:8px;
}
td {
    min-width: 80px;
}
td.header {
    font-weight:600;
}
td.value {
     font-weight: 400;
    text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body id="emp_body">

<body>

如有任何更改,请发表评论。