表内的DIV到JSON到

时间:2014-02-12 12:22:52

标签: jquery json dom html-table

DOM中有2个表,我正在尝试将<div>中带有类test的表中的数据转换为JSON,但它无法正常工作。此外,我需要访问<div>内的表格的特定单元格值。

<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>

1 个答案:

答案 0 :(得分: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"]}