在数组数组中查找表数据存储

时间:2013-12-12 19:51:01

标签: javascript arrays

我需要从表中获取数据并将其存储在数组中。表的每一行都应该是数组中的新数组。基本上html看起来像这样:

<table id="contactlisttable">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Phone</th>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Joey</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone">5555555</td>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Anthony</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone">5555555</td>
    </tr>
</table> 

等...

这是我的代码

jQuery(document).ready(function(){
    $(function(){
        var $table = $("#contactlisttable"),
        $headerCells = $table.find("tr th"),
        $myrows = $table.find("tr"); // Changed this to loop through rows

        var headers = [],
            rows = [];

        $headerCells.each(function() {
            headers[headers.length] = $(this).text();
        });

        $myrows.each(function() {
            $mycells = $myrows.find( "td.contactlist" ); // loop through cells of each row
            cells = []
            $mycells.each(function() {
                cells.push($(this).text());
            });
            if ( cells.length > 0 ) {
                rows.push(cells);
            }  
        });
        console.log(headers);
        console.log(rows);
    }); 
});

我当前的代码输出

[["Waddell, Joey", "webdesigner", "", 15 more...], ["Waddell, Joey", "webdesigner", "", 15 more...],

所需的输出是:

["Name","Title","Phone"]
[["Joey","webdesigner","555555"]
["Anthony","webdesigner","555555"]]

1 个答案:

答案 0 :(得分:0)

我认为这可以更简单:

Live Demo

<强> JS

$(function(){
    var results = []; 
    var row = -1; 
    $('#contactlisttable').find('th, td').each(function(i, val){
        if(i % 3 === 0){ //New Row? 
            results.push([]); 
            row++;//Increment the row counter
        }
        results[row].push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)       
    }); 
    console.log(results); 
}); 

修改

这是一个更好的解决方案(IE9 +兼容)。与以前的解决方案不同,它可以解释变量行长度。

Live Demo

<强> JS

//IE9+ compatable solution
$(function(){
    var results = [], row; 
    $('#contactlisttable').find('th, td').each(function(){
        if(!this.previousElementSibling){ //New Row?
            row = []; 
            results.push(row); 
        }
        row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)       
    }); 
    console.log(results); 
});