简体   繁体   中英

How to loop unique target ID? [jQuery]

How to assign unique target ID into individual row of JSON data? In this case, all row using the same name which is data-target=".childData" . How to assign different incremental name such as .childData , .childData2 , .childData3 and so on in jQuery etc?

$.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>"
    );
  });
});

$.each(data, function(i, item) : here i is actually the index of your array. So you can add this index when generating the html.

Replace

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

with this-

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

Mahbub Moon solution should work. But it's not recommended to use a same id for several html components.

You should replace

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

by

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM