Appending tr to thead using jQuery results blank t

2019-02-28 09:09发布

I am trying to create thead with tr, from JSON object array. This is required as it's needed by jQuery datatable.

I have following script to do that, but creates tr with blank values.

$(function() {
  var json = {
    "Number": "10031",
    "Description": "Solid Parts",
    "Factory": "Factory1",
    "LocationIn": "OutRack",
    "Quantity": 18
  }

  var parsed = $.parseJSON(JSON.stringify(json));
  console.log(parsed);

  var $thead = $('#tableId').find('thead');
  $.each(parsed, function(name, value) {
    $thead.append('<tr>' + name + '</tr>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableId" class="table table-condensed responsive">
  <thead>
  </thead>
  <tbody>
  </tbody>
</table>

I need a table to be created with array name. Example:

<table id="tableId" class="table table-condensed responsive">
  <thead>
    <tr>Number</tr>
    <tr>Description</tr>
    <tr>Factory</tr>
    <tr>LocationIn</tr>
    <tr>Quantity</tr>
  </thead>
  <tbody>
  </tbody>
</table>

1条回答
趁早两清
2楼-- · 2019-02-28 10:03

Within a tr in thead... Ususally (that is sarcastic a bit), you need some th to display text.

$(function() {

    var json = {
        "Number": "10031",
        "Description": "Solid Parts",
        "Factory": "Factory1",
        "LocationIn": "OutRack",
        "Quantity": 18
    }

    var parsed = $.parseJSON(JSON.stringify(json));
    console.log(parsed);

    var $thead = $('#tableId').find('thead');
    var $tr = $("<tr>");
    $.each(parsed, function(name, value) {
        $tr.append('<th>' + name + '</th>');
    });
    $thead.append($tr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableId" class="table table-condensed responsive">
    <thead>
    </thead>
    <tbody>

    </tbody>
</table>

查看更多
登录 后发表回答