如何在表中求和TR

如何在表中求和TR

<table id="tab" border="1">
    <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
        <td>D</td>
    </tr>
    <tr>
        <td>2</td>
        <td>2</td>
        <td>2</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td>3</td>
        <td>3</td>
        <td>3</td>
    </tr>
    <!-- HERE IS SUM -->
    <tr>
        <td>?</td>
        <td>?</td>
        <td>?</td>
        <td>?</td>
    </tr>
</table>


我想将所有的数据加起来,这些数据来自迭代

因此,当有10行数据时,那么10行将加起来

for example
A  B  C  D
2  2  2  2
3  3  3  3
SUM
5  5  5  5

最佳答案

您可以querySelector所有行,删除第一行并获取最后一行以填充值,每行querySelector其列和我都使用过ES6映射并归约来累积值



const rows = Array.from(document.querySelectorAll('tr'));
const lastRow = rows.splice(rows.length - 1, 1)[0];
// Remove first row
rows.splice(0,1);

const sumArr = rows.reduce((acc,row) => {
   const cols = row.querySelectorAll('td');
   return acc.map((c, i) => c + +cols[i].innerHTML);
}, [0,0,0,0]);

const lastRowCols = lastRow.querySelectorAll('td');

sumArr.forEach((s, i) => {
  lastRowCols[i].innerHTML = s;
})

<table id="tab" border="1">
    <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
        <td>D</td>
    </tr>
    <tr>
        <td>2</td>
        <td>2</td>
        <td>2</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td>3</td>
        <td>3</td>
        <td>3</td>
    </tr>
    <!-- HERE IS SUM -->
    <tr>
        <td>?</td>
        <td>?</td>
        <td>?</td>
        <td>?</td>
    </tr>
</table>

关于javascript - 如何在表中求和TR,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60428131/

10-11 04:21