2014-02-12 30 views
0

DOM中有2個表格,我試圖將<div>中的表格中的數據與類別test轉換爲JSON,但它不起作用。另外,我需要訪問<div>中表格的特定單元格值。DIV到JSON中的表格到

<table> 
    <thead> 
     <tr> 
      <th>Column 9</th> 
      <th>Column 2</th> 
      <th>Column 7</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td>A6</td> 
      <td>A2</td> 
      <td>A3</td> 
     </tr> 
     <tr> 
      <td>B4</td> 
      <td>B2</td> 
      <td>B3</td> 
     </tr> 
     <tr> 
      <td>C1</td> 
      <td>C8</td> 
      <td>C9</td> 
     </tr> 
    </tbody> 
</table> 
</table> 
<div class="test"> 
    <table> 
     <thead> 
      <tr> 
       <th>Column 1</th> 
       <th>Column 2</th> 
       <th>Column 3</th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr> 
       <td>A1</td> 
       <td>A2</td> 
       <td>A3</td> 
      </tr> 
      <tr> 
       <td>B1</td> 
       <td>B2</td> 
       <td>B3</td> 
      </tr> 
      <tr> 
       <td>C1</td> 
       <td>C2</td> 
       <td>C3</td> 
      </tr> 
     </tbody> 
    </table> 
</div> 
<script> 
    cvar myRows = []; 
    var $headers = $("th"); 
    var $rows = $(".test tbody tr").each(function(index) { 
     $cells = $(this).find("td"); 
     myRows[index] = {}; 
     $cells.each(function(cellIndex) { 
     myRows[index][$($headers[cellIndex]).html()] = $(this).html(); 
     });  
    }); 
    var myObj = {}; 
    myObj.myrows = myRows; 
    alert(JSON.stringify(myObj)); 
</script> 

回答

0

這是你在找什麼:

$(function() { 
    var myMap = {};  
    $(".test tbody tr").each(function(index) { 
     var header = $(".test thead tr th").eq(index).text();    

     myMap[header] = $(this).find("td").map(function() { 
      return $(this).text(); 
     }).get();   
    });         

    console.log(JSON.stringify(myMap)); 
}); 

輸出:

{"Column 1":["A1","A2","A3"], 
"Column 2":["B1","B2","B3"], 
"Column 3":["C1","C2","C3"]} 
+0

這是不與該臺工作 –