使用jquery逐行获取表格单元格值

时间:2012-09-13 15:54:22

标签: jquery

我有一张这样的表

<table class="wp-list-table widefat fixed posts">
        <tbody id="c_b">
    <tr>
        <td><b>Title</b></td>
        <td><b>Upcharge</b></td>
        <td><b>Profit Percentage</b></td>
        <td><b>Short Description</b></td>
    </tr>
    <tr>
        <td colspan="4"><input type="checkbox" id="selectall"> Bulk <u>Check/Uncheck</u></td>
    </tr>
    <tr>
        <td id="title_1"><input type="checkbox" id="product_1" value="123123_1" class="case"> 123123<br></td>
        <td id="upcharge_1">24</td>
        <td id="percentage_1">15</td>
        <td id="sdescription_1">This is a short</td>
    </tr>
    <tr>
        <td id="title_2"><input type="checkbox" id="product_2" value="A33232_2" class="case"> A33232<br></td>
        <td id="upcharge_2">24</td>
        <td id="percentage_2">15</td>
        <td id="sdescription_2">This is a short</td>
    </tr>
    <tr>
        <td id="title_22"><input type="checkbox" id="product_3" value="BEY-049_22" class="case"> Plane Shirt<br></td>
        <td id="upcharge_22">24</td>
        <td id="percentage_22">15</td>
        <td id="sdescription_22">SD for Plane shirt</td>
    </tr>
    <tr>
        <td id="title_23"><input type="checkbox" id="product_4" value="IRCTC_23" class="case"> Rail Neer<br></td>
        <td id="upcharge_23">24</td>
        <td id="percentage_23">15</td>
        <td id="sdescription_23">Rail neer short description</td>
    </tr>
    <input type="hidden" value="47474" id="licence_no" name="licence_no"><input type="hidden" value="47474" id="licence_no" name="licence_no">
    <input type="hidden" value="47474" id="licence_no" name="licence_no"><input type="hidden" value="47474" id="licence_no" name="licence_no">      
    </tbody>
    </table>

我希望逐行将单元格值作为数组,为此我编写如下代码

$("tbody>tr").each(function(){
        var rowvalue = [];
        $("tbody>tr>td").each(function(){
            //alert($(this).text());
            rowvalue.push($(this).text());
        });
        alert(rowvalue);

    });

这里我一次调整所有值并且它会发出n次警报(n =行数),但是我想要n个带有行值的数组。我怎样才能获得这些价值。

2 个答案:

答案 0 :(得分:4)

你可以使用它,

var rowvalues = [];
            $("tbody > tr").each(function () {
                var rowvalue = [];
                $(this).children().each(function () {
                    //alert($(this).text());
                    rowvalue.push($(this).text());
                });
                rowvalues.push(rowvalue);
            });

这里rowvalues数组将包含行方式值

答案 1 :(得分:2)

演示:http://jsfiddle.net/iambriansreed/2Pgey/

var table_data = [];

$('tr').each(function(){

    var row_data = [];    

    $('td', this).each(function(){

        row_data.push($(this).text());   

    });    

    table_data.push(row_data);

});

console.log(table_data);