在tr中然后在tbody中附加td

时间:2019-02-04 01:08:45

标签: javascript jquery html append

我有下一个代码:

var data_object =[{"data1":"DATA1","data2":"DATA2","data3":"DATA3"}]

var tr;
for (var ctr = 0; ctr < data_object.length; ctr++) {
  tr = $("<tr></tr>");
  tr.append("<td>" + data_object[ctr].data1 ? data_object[ctr].data1 : '' + "</td>");
  tr.append("<td>" + data_object[ctr].data2 ? data_object[ctr].data2 : '' + "</td>");
  tr.append("<td>" + data_object[ctr].data3 ? data_object[ctr].data3 : '' + "</td>");

  $('#tblAutoMatch tbody').append(tr)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblAutoMatch" class="table table-bordered" width="100%">
  <thead>
    <tr>
      <th class="col-md-1" style="text-align: center; width: 5%;">Data 1</th>
      <th class="col-md-1" style="text-align: center; width: 13%;">Data 2</th>
      <th class="col-md-1" style="text-align: center; width: 13%;">Data 3</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

但是,有一个问题:为什么td没有附加到tr中?我只在tr中收到文本。

1 个答案:

答案 0 :(得分:3)

您需要使用括号(...)来包装使用三元运算符的表达式,例如:

tr.append("<td>" + (data_object[ctr].data1 ? data_object[ctr].data1 : '') + "</td>");

因此,它们将按照您的期望进行评估。否则,您的表达式将按以下方式求值:

tr.append(("<td>" + data_object[ctr].data1) ? data_object[ctr].data1 : ('' + "</td>"));

并且将减少为data_object[ctr].data1,因为("<td>" + data_object[ctr].data1)将被评估为true

$(document).ready(function()
{
    var data_object = [
      {"data1":"DATA1","data2":"DATA2","data3":"DATA3"}
    ];

    var tr;
    
    for (var ctr = 0; ctr < data_object.length; ctr++)
    {
        tr = $("<tr>");
        tr.append("<td>" + (data_object[ctr].data1 ? data_object[ctr].data1 : '') + "</td>");
        tr.append("<td>" + (data_object[ctr].data2 ? data_object[ctr].data2 : '') + "</td>");
        tr.append("<td>" + (data_object[ctr].data3 ? data_object[ctr].data3 : '') + "</td>");

        $('#tblAutoMatch tbody').append(tr)
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="tblAutoMatch" class="table table-bordered" width="100%">
  <thead>
    <tr>
      <th class="col-md-1" style="text-align: center; width: 5%;">Data 1</th>
      <th class="col-md-1" style="text-align: center; width: 13%;">Data 2</th>
      <th class="col-md-1" style="text-align: center; width: 13%;">Data 3</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>