简体   繁体   中英

Incorrect Rendering of Table Columns from JSON Data

I have the following JSON structure:

{"rows": [

      {"row":[  
             {"cells": [
                   {"data": "Edit"},
                   {"data": "Add"}
             ]}
      ]},
      {"row":[
             {"cells": [
                   {"data": 1},
                   {"data": 2}
             ]}
      ]}
]} 

For every "row" in the JSON file, there will be a table row and for every "data" a row column.

My code looks like this:

$.each(response.rows, function(index, rows){

     $.each(rows.row, function(index, row){
          $("tbody").append("<tr>"); 
          $.each(this.cells, function(){ 
               $("tr").append("<td>" + this.data + "</td>");
          });
          $("tbody").append("</tr>");
     });
}); 

My code is generating the table rows/columns like this:

Row 1 -- I get 4 columns with values "Edit"/"Add"/1/2 
Row 2 -- I get 2 columns with values 1/2. 

If I add another "row" in JSON file, then Row 1 & 2 are rendered incorrectly.

Row 1 should only have 2 columns with values "Edit"/"Add". The JSON structure seems right.

Can someone please tell me what I'm doing wrong? Thank you.

It's your syntax: http://jsfiddle.net/SXzny/ That fixes it, because it doesn't reference all tags, but the one you created.

For example, replace:

$.each(rows.row, function(index, row){
  $("tbody").append("<tr>"); 
  $.each(this.cells, function(){ 
       $("tr").append("<td>" + this.data + "</td>");
  });
  $("tbody").append("</tr>");
});

with:

$.each(rows.row, function(index, row){
  var element = $("tbody").append("<tr>"); 
  $.each(this.cells, function(){ 
       element.append("<td>" + this.data + "</td>");
  });
  $("tbody").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