2014-07-22 2 views
0

테이블의 첫 번째 행을 반환 잘 작동합니다. 기능을 원하는 목적으로 사용하는 구조화 된 코드가 필요합니다.JS 나는 다음과 같은 한

  • 테이블을 작성하는 기능과 appendi 그것을 (첫 번째 예에서와 같이).

JSON 형식 :

var source = { 
    "Products": [ 
     { 
      "Product": "xxxxx.com", 
      "Bookings": 560, 
      "Percentage": 55.82, 
      "Transactions": "xxxx.xx" 
     }, 
     { 
      "Product": "xxxxx Mobile", 
      "Bookings": 487, 
      "Percentage": 9.12, 
      "Transactions": "xxxx.xx" 
     }, 
     { 
      "Product": "xx 24-7", 
      "Bookings": 478, 
      "Percentage": 8.95, 
      "Transactions": "xxxx.xx" 
     }, 
     { 
      "Product": "xxxxxx", 
      "Bookings": 422, 
      "Percentage": 7.9, 
      "Transactions": "xxxx.xx" 
     }, 
     { 
      "Product": "API", 
      "Bookings": 315, 
      "Percentage": 5.9, 
      "Transactions": "xxxx.xx" 
     }, 
     { 
      "Product": "API", 
      "Bookings": 315, 
      "Percentage": 2.83, 
      "Transactions": "xxxx.xx" 
     } 
    ], 
    "Total": { 
     "Bookings": 315, 
     "Transactions": "xxxx.xx" 
    } 
} 

어떤 도움?

답변

1
function builTable(){ 
    var table = ""; 

    for(i = 0; i< source.Products.length; i++){ 

     var sourceProducts = source.Products[i], 
      row = '<tr><td>sth</td><td>'; 

     row += sourceProducts.Product; 
     row += '</td><td>'; 
     row += sourceProducts.Bookings + '</td><td>'; 
     row += sourceProducts.Percentage + '%' + '</td><td>'; 
     row += sourceProducts.Transactions + '</td></tr>'; 

     table += row; 

    } 

    return table; 
    } 

    function generateTable(){ 
    $('table').append(builTable()); 
    } 

    $(document).ready(function(){ 

    generateTable(); 

    }); 
+0

것은 나를 비트) – Cameron

1

row 루프가 다시 시작 때마다 리셋이기 때문입니다.

function builTable(){ 
    for(i = 0; i< source.Products.length; i++){ 

     var sourceProducts = source.Products[i]; 

      // here is the culprit 
      row = '<tr><td>sth</td><td>'; 


      row += sourceProducts.Product; 
      row += '</td><td>'; 
      row += sourceProducts.Bookings + '</td><td>'; 
      row += sourceProducts.Percentage + '%' + '</td><td>'; 
      row += sourceProducts.Transactions + '</td></tr>'; 

      return row; 

    } 

    }