简体   繁体   中英

how to dynamically append tr element with css to a table

I am looping through $.each in jquery and getting back data and appending that data to a table like this:

 $.each(segment, function (index, innerSegment) {
 var tr;
 tr = $('<tr/>');
 tr.append("<td>" + segment[i].Airline.AirlineName + "</td>");

 tr.append("<td>" + segment[i].ArrivalTime + "</td>");
 tr.append("<td>" + segment[i].Origin "</td>"); 

 tr.append("<td>" + segment[i].DepartureTime + "</td>");
 tr.append("<td>" + segment[i].Destination "</td>"); 

 tr.append("<td>" + segment[i].Duration + "</td>");
 tr.append("<td>" + segment[i].publishedFare "</td>");
 $('#tableId').append(tr);
}

Now, I am getting back proper data from $.each loop. But all the data is appending one after the another.

I want to append the data something like this in this jsfiddle. https://jsfiddle.net/1pbso9jt/

My table is like this:

<table id="tableId">
     <tr>   
       </tr>
 </table>

How's this:

var table = $('#tableId');
$.each(segment, function (index, innerSegment) {
  var rows = '<tr><td rowspan="4" width="25%">' + segment[i].Airline.AirlineName + "</td>";
  rows += '<td width="25%">' + segment[i].ArrivalTime + "</td>";
  rows += '<td rowspan="4" width="25%">&nbsp;</td>';
  rows += '<td rowspan="4" width="25%">' + segment[i].publishedFare + "</td></tr>";
  rows += "<tr><td>" + segment[i].Origin + "</td></tr>"; 
  rows += "<tr><td>" + segment[i].DepartureTime + "</td></tr>";
  rows += "<tr><td>" + segment[i].Destination + "</td></tr>"; 

  table.append(rows);
});

Example fiddle with the each commented out

Updated fiddle with your data

You should combine your jsfiddle with the loop, like this:

$.each(segment, function (index, innerSegment) {
  var output;
  output = $('<table border="1"style="width:100%"><tr>');
  output.append("<td rowspan="4"style="width:25%">" + segment[i].Airline.AirlineName + "</td>");
  output.append("<td height="58">" + segment[i].ArrivalTime + "</td>");
  ...
  etcetera
  ...
  $('#tableId').append(output);
}

Try This :-

$.each(segment, function (index, innerSegment) {
 var tr;
 tr = "<tr/>";
 tr+= "<td>" + segment[i].Airline.AirlineName + "</td>";

 tr+= "<td>" + segment[i].ArrivalTime + "</td>";
 tr+= "<td>" + segment[i].Origin "</td>";

 tr+= "<td>" + segment[i].DepartureTime + "</td>";
 tr+= "<td>" + segment[i].Destination "</td>"; 

 tr += "<td>" + segment[i].Duration + "</td>";
 tr += "<td>" + segment[i].publishedFare "</td>";
 $('#tableId').append(tr);
}

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