如何循环唯一目标ID? [jQuery]

时间:2019-11-17 09:54:05

标签: javascript jquery

如何为JSON数据的各个行分配唯一的目标ID?在这种情况下,所有行都使用相同的名称,即data-target=".childData"。如何在jQuery等中分配不同的增量名称,例如.childData.childData2.childData3等?

$.post('requestForm_table.php', function (data) {
  $.each(data, function (i, item) {
    //calStatus = item.status;

    $("#formAll").append("<tr id=\"highlight\" data-toggle=\"collapse\" data-target=\".childData\">" +
      "<td>" + item.id + "</td>" +
      "<td>" + item.ein_number + "</td>" +
      "<td>" + item.instrumentDesc + "</td>" +
      "<td>" + item.dateReceived + "</td>" +
      "<td>" + item.siteCode + "</td>" +
      "<td class=\"text-success text-center\">" + "<span class=\"statusColor\" style=\" font-style: italic;\">" + item.status + "</span>" + "</td>" +
      "</tr>" +
      "<tr>" +
      "<td colspan=6 class=\"hiddenRow\">" +
      "<div class=\"collapse childData ml-5\" style=\"font-size: 13px\">" +
      "<div class=\"row\">" +
      "<div class=\"col-4\">" + "Calibration Job: " + item.status + "</div>" +
      "<div class=\"col-4\">" + "Owner: " + item.owner + "</div>" +
      "<div class=\"col-4\">" + "Serial Number: " + item.serialNum + "</div>" +
      "</div>" +
      "<div class=\"row\">" +
      "<div class=\"col-4\">" + "Date Received:  " + item.dateReceived + "</div>" +
      "<div class=\"col-4\">" + "Calibration Cost: " + item.calCost + "</div>" +
      "<div class=\"col-4\">" + "Manufacturer: " + item.manufacturer + "</div>" +
      "</div>" +
      "</div>" +
      "</td>" +
      "</tr>"
    );
  });
});

2 个答案:

答案 0 :(得分:1)

$.each(data, function(i, item):此处i实际上是数组的索引。因此,您可以在生成html时添加此索引。

替换

$("#formAll").append("<tr id=\"highlight\" data-toggle=\"collapse\" data-target=\".childData\">"

与此-

$("#formAll").append("<tr id=\"highlight"+i+"\" data-toggle=\"collapse\" data-target=\".childData"+i+"\">"

答案 1 :(得分:0)

Mahbub Moon解决方案应该起作用。 但不建议对多个html组件使用相同的ID。

您应该替换

$("#formAll").append("<tr id=\"highlight\" data-toggle=\"collapse\" data-target=\".childData\">"

通过

$("#formAll").append("<tr id=\"highlight" + i + "\" data-toggle=\"collapse\" data-target=\".childData"+i+"\">"