从动态表jQuery获取所有行

时间:2016-07-04 09:14:59

标签: javascript jquery html dynamic-tables

我正在尝试从动态表中读取所有行。主要思想是读取所有行并将其存储在数组中以供进一步处理。但到目前为止,我还没能得到行数据。下面的代码只返回表头。

以下是代码:

var data = [];

var i = 0;

$('#tempTable td').each(function (index, tr) {
    var tds = $(tr).find('td');

    if (tds.length > 1) {
        data[i++] = {
            action: tds[0].textContent,
            spec: tds[1].textContent,
            data: tds[2].textContent,
            unit: tds[3].textContent,
            upper_tol: tds[4].textContent,
            lower_tol: tds[5].textContent,
            tol_unit: tds[6].textContent,
            def: tds[7].textContent
        }
    }
});

HTML标记如下所示:

<table id='tempTable'>
    <thead>
        <tr>
            <td class='table_head' width='80px'>Header1</td>
            <td class='table_head' width='435px'>Header2</td>
            <td class='table_head' width='100px'>Header3</td>
            <td class='table_head' width='100px'>Header4</td>
            <td class='table_head' width='100px'>Header5</td>
            <td class='table_head' width='100px'>Header6</td>
            <td class='table_head' width='100px'>Header7</td>
            <td class='table_head' width='80px'>Header8</td>
        </tr>
    </thead>
    <tbody>
        <!-- Rows inserted dynamically here using jQuery -->
    </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

您已将表格标题初始化为“td”,而您需要在“th”中初始化它们,如下所示。

<table id='tempTable'>
    <thead>
        <tr>
            <th class='table_head' width='80px'>Header1</th>
            <th class='table_head' width='435px'>Header2</th>
            <th class='table_head' width='100px'>Header3</th>
            <th class='table_head' width='100px'>Header4</th>
            <th class='table_head' width='100px'>Header5</th>
            <th class='table_head' width='100px'>Header6</th>
            <th class='table_head' width='100px'>Header7</th>
            <th class='table_head' width='80px'>Header8</th>
        </tr>
    </thead>
    <tbody>
        <!-- Rows inserted dynamically here using jQuery -->
    </tbody>
</table>

另请参阅选择表数据的事件(选择表之前应填充数据)。

用于从表格中选择数据:

//traverse each row
$('#tempTable tr').each(function (index, tr) {
    var cols = [];

    //get td of each row and insert it into cols array
    $(this).find('td').each(function (colIndex, c) {
        cols.push(c.textContent);
    });

    //insert this cols(full rows data) array into tableData array
    tableData.push(cols);
  });

  console.log("tableData: ", tableData);

请找到相同的小提琴https://jsfiddle.net/Prakash_Thete/frm2ebug/1/ ..