我如何从表的每一行获取值并将其存储在js数组中

时间:2019-02-26 11:21:22

标签: javascript html jsp struts

我有这段代码生成一个html表,我想在单击按钮时从行中获取所有数据,并将其存储在js数组中。

    <table cellpadding="0" cellspacing="0" width="25%" style="margin-top: 3em;" align="center">
<tr align="center">
    <td>&nbsp;</td>
    <td colspan="2" style="font-size:small;">Anualitat seleccionable</td>   
</tr>

<tr align="center">
    <td class="tau4">&nbsp;</td>
    <td class="tau4">Empleat</td>
    <td class="tau4">Gestor</td>    
</tr>
<logic:iterate id="i" name="anys_irpf" indexId="count">
    <tr align="center" class="dadesAnys">
        <td class="tau2" width="30%">${i.any}</td>
        <td class="tau2" width="35%">
            <c:choose>
                <c:when test="${i.anyEmpleat == 1}">
                    <input type="checkbox" id="cbox1" value="cbox1" checked>
                </c:when>
                <c:otherwise>
                    <input type="checkbox" id="cbox1" value="cbox1">
                </c:otherwise>
            </c:choose>
        </td>
        <td class="tau2" width="35%">
            <c:choose>
                <c:when test="${i.anyGestor == 1}">
                    <input type="checkbox" id="cbox2" value="cbox2" checked>
                </c:when>
                <c:otherwise>
                    <input type="checkbox" id="cbox2" value="cbox2">
                </c:otherwise>
            </c:choose>
        </td>
    </tr>
</logic:iterate>
</table>

这是生成表的代码。

2 个答案:

答案 0 :(得分:0)

为该行的所有td标签赋予相同的类名, 因此,当您单击按钮时,获取类名称的所有元素,并在for循环中添加该元素的所有值

答案 1 :(得分:0)

var myTab = document.getElementById('tableID');
        var tableData = [];
    // LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
    for (i = 1; i < myTab.rows.length; i++) {

        // GET THE CELLS COLLECTION OF THE CURRENT ROW.
        var objCells = myTab.rows.item(i).cells;

        // LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
        for (var j = 0; j < objCells.length; j++) {
            tableData.push(objCells.item(j).innerHTML);
            }

    }