【问题标题】:Table inside a DIV to JSON to [closed]将 DIV 中的表转换为 JSON 到 [关闭]
【发布时间】:2014-03-10 18:33:58
【问题描述】:

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>

【问题讨论】:

    标签: jquery json dom html-table


    【解决方案1】:

    这是你要找的东西吗:

    $(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"]} 
    

    【讨论】:

    • 这不适用于表格
    猜你喜欢
    • 2012-12-09
    • 2011-07-08
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2010-10-14
    相关资源
    最近更新 更多