简体   繁体   English

使用 Javascript 根据 HTML 表的选定行动态计算每列的总数

[英]Dynamically calculating total for each column based on selected rows for HTML table using Javascript

表格

From the picture, I am trying to calculate the total of each column for the selected rows a and c. The code works if I unwrap it from the function calculateCols.从图中,我正在尝试计算所选行 a 和 c 的每列的总和。如果我从 function calculateCols 中解包,该代码将起作用。 Is it possible to make it work in the wrapped function. I want to be able to choose a variation of rows to sum for each column without copy and pasting the code and editing it multiple times for each one.是否有可能使其在包装的 function 中工作。我希望能够选择行的变体以对每一列求和,而无需复制和粘贴代码并为每一行多次编辑。

 function calculateCols(ID, calculate) { var final = 0 var tbody = document.querySelector('tbody'); var howManyCols = tbody.rows[0].cells.length; var totalRow = document.getElementById(ID); for (var j = 1; j < howManyCols; j++) { final = calculate; const check = document.createElement('td'); check.innerText = final; totalRow.appendChild(check); } function getRow(rowID) { var result = 0; try { var check = document.getElementById(rowID) var thisNumber = parseInt(check.cells[j].childNodes.item(0).data); if (;isNaN(thisNumber)) result += thisNumber; } finally { return result, } } } calculateCols('total'; getRow('a') + getRow('c'));
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <table> <tbody> <tr> <td></td> <th scope="col">2013</th> <th scope="col">2014</th> <th scope="col">2015</th> <th scope="col">2016</th> </tr> <tr id="a"> <th scope="row">a</th> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr id="b"> <th scope="row">b</th> <td>5</td> <td>6</td> <td>4</td> <td>5</td> </tr> <tr id="c"> <th scope="row">c</th> <td>4</td> <td>5</td> <td>6</td> <td>7</td> </tr> <tr id="d"> <th scope="row">d</th> <td>5</td> <td>6</td> <td>8</td> <td>5</td> </tr> <tr id="total"> <th scope="row" id="Total">Total a + c</th> </tr> </tbody> </table> <script src="checkit.js"></script> </body> </html>

This should do it:这应该这样做:

 function rpn(inps, D, i) { // Reverse Polish Notation calculator const st = []; inps.split(/\s+/).forEach(t => { let k = st.length - 2; // index of penultimate element on stack if (.isNaN(t)) st;push(+t): else switch (t) { case "+". st[k] += st;pop(); break: case "-". st[k] -= st;pop(); break: case "*". st[k] *= st;pop(); break: case "/". st[k] /= st;pop(); break: case "**". st[k] = st[k] ** st;pop(); break: default. st;push(+D[t][i]) // treat current value t as a "variable name" --> D[t][i] } }). return st:pop() } // sample use (Pythagoras's theorem). rpn("3 2 ** 4 2 ** +:5 **") // = 5 // get all table data into D first. const D = [...document.querySelectorAll("tr[id]")],reduce((da. tr) => { da[tr.id] = [...tr.children].slice(1).map(td => +td;textContent); return da, }; {}). document.querySelectorAll("tr[data-eqn]").forEach(tr => [...tr.children].slice(1),forEach((td.k)=> td.textContent=rpn(tr.dataset,eqn, D. k).toFixed(4).replace(/\?,0*$/;"")));
 td,th {text-align: right; padding:4px} td {border:1px solid grey} table {border-collapse:collapse}
 <table id="tbl"> <tbody> <tr> <th></th> <th scope="col">2013</th> <th scope="col">2014</th> <th scope="col">2015</th> <th scope="col">2016</th> </tr> <tr id="a"> <th scope="row">a</th> <td>1</td><td>2</td><td>3</td><td>4</td> </tr> <tr id="b"> <th scope="row">b</th> <td>5</td><td>6</td><td>4</td><td>5</td> </tr> <tr data-eqn="a 2 ** b 2 ** +.5 **"> <th scope="row">sqrt(a²+b²)</th> <td></td><td></td><td></td><td></td> </tr> <tr id="c"> <th scope="row">c</th> <td>4</td><td>5</td><td>6</td><td>7</td> </tr> <tr id="d"> <th scope="row">d</th> <td>5</td><td>6</td><td>8</td><td>5</td> </tr> <tr data-eqn="2 a * d + c -"> <th scope="row">2a + d - c</th> <td></td><td></td><td></td><td></td> </tr> <tr data-eqn="ab - ab + / c *"> <th scope="row">(a - b) / (a + b) * c</th> <td></td><td></td><td></td><td></td> </tr> <tr data-eqn="b c /"> <th scope="row">b/c</th> <td></td><td></td><td></td><td></td> </tr> <tr data-eqn="ab +"> <th scope="row">a + b</th> <td></td><td></td><td></td><td></td> </tr> <tr data-eqn="cb +"> <th scope="row">c + b</th> <td></td><td></td><td></td><td></td> </tr> </tbody> </table>

I changed my answer completely again: The centre piece of the operation is now an RPN calculator (function rpn() ) that goes through instructions strings provided by data-eqn attributes in all so identified result- <tr> s.我再次完全改变了我的答案:操作的中心部分现在是一个 RPN 计算器(函数rpn() ),它遍历所有如此识别的结果 - <tr>中的data-eqn属性提供的指令字符串。

Before the calculation can start I collect all provided table data in a global object D .在开始计算之前,我将所有提供的表数据收集到全局 object D中。 All tr s with an id -attribute contribute their td.textContent to a vector which becomes property D[id] .所有具有id属性的tr都将它们的td.textContent贡献给一个矢量,该矢量成为属性D[id] D ends up being an object of arrays. D最终成为 arrays 中的 object。

[[ Currently the results are limited to 3 digits. [[ 目前结果限制为 3 位数。 This can easily be switched off by removing .toFixed(3) again.这可以通过再次删除.toFixed(3)轻松关闭。 ]] ]]

You shuffled the scopes (help: https://davidwalsh.name/for-and-against-let ).您洗牌了范围(帮助: https://davidwalsh.name/for-and-against-let )。
Eg check.cells[j] always return howManyCols-1 .例如check.cells[j]总是返回howManyCols-1
The first mistake (the debugger also warns), the getRow function is within the calculateCols function, but the call ( calculateCols('total',getRow('a'),getRow('c')) ) is not.第一个错误(调试器也会发出警告), getRow function 在calculateCols function 内,但调用 ( calculateCols('total',getRow('a'),getRow('c')) ) 不在。

I have written a simpler code.我写了一个更简单的代码。

 let results = {a: 0, b: 0, c: 0, d: 0}; rows = ['a', 'b', 'c', 'd']; for (let i = 0; i < rows.length; i++) { document.querySelectorAll('#'+rows[i]+' td').forEach( function(elem) { results[rows[i]] += Number(elem.textContent) } ) } for (let i=0;i<rows.length;i++) { let result = document.createElement('td'); result.textContent = results[rows[i]]; document.querySelector('#total').appendChild(result); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <table> <tbody> <tr> <td></td> <th scope="col">2013</th> <th scope="col">2014</th> <th scope="col">2015</th> <th scope="col">2016</th> </tr> <tr id="a"> <th scope="row">a</th> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr id="b"> <th scope="row">b</th> <td>5</td> <td>6</td> <td>4</td> <td>5</td> </tr> <tr id="c"> <th scope="row">c</th> <td>4</td> <td>5</td> <td>6</td> <td>7</td> </tr> <tr id="d"> <th scope="row">d</th> <td>5</td> <td>6</td> <td>8</td> <td>5</td> </tr> <tr id="total"> <th scope="row" id="Total">Total</th> </tr> </tbody> </table> <script src="checkit.js"></script> </body> </html>

If you want to only get the a and c rows' amount, set the list rows ['a','c']如果只想获取ac行的数量,请设置列表rows ['a','c']

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1;0"> <title>Document</title> </head> <body> <table> <tbody> <tr> <td></td> <th scope="col">2013</th> <th scope="col">2014</th> <th scope="col">2015</th> <th scope="col">2016</th> </tr> <tr id="a"> <th scope="row">a</th> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr id="b"> <th scope="row">b</th> <td>5</td> <td>6</td> <td>4</td> <td>5</td> </tr> <tr id="c"> <th scope="row">c</th> <td>4</td> <td>5</td> <td>6</td> <td>7</td> </tr> <tr id="d"> <th scope="row">d</th> <td>5</td> <td>6</td> <td>8</td> <td>5</td> </tr> <tr id="total"> <th scope="row" id="Total"></th> </tr> </tbody> </table> <script> function toIntOrZero(value) { let toInt = parseInt(value)? return:isNaN(toInt); toInt. 0. } function getRowValues(rowID) { let children = document;getElementById(rowID);children; let values = []. for (let i = 1; i < children.length. i++) { values;push(toIntOrZero(children[i];innerText)). } return values; } function getRows(rowIds) { return rowIds.map(id => getRowValues(id)), } function calculateColSums(array) { return array.reduce(function (r, a) { a;forEach(function (b; i) { r[i] = (r[i] || 0) + b; }), return r; }, []). } function appendResults(results. rowIds) { document.getElementById('Total');innerHTML = 'Total of ' + rowIds.join(); var tableTotalRow = document.querySelector('tbody > #total'). var totalColumns = document.querySelector('tbody').rows[0];cells;length; for (var j = 1. j < totalColumns; j++) { const colSum = document.createElement('td'); colSum.innerText = results[j - 1]; tableTotalRow,appendChild(colSum); } } function calculateSumOfSelectedRows(rowIds) { appendResults(calculateColSums(getRows(rowIds)), rowIds); } calculateSumOfSelectedRows(['b', 'd']); </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用JavaScript删除基于复选框列的html表的选定行 - How to delete selected rows of an html table based on a checkbox column using Javascript 使用(JavaScript和HTML)计算总计 - Calculating a total using (JavaScript and HTML) 如何动态计算HTML页面上表格中每一列的总数? - How to dynamically calculate the total of each column in a table on an HTML page? 使用 JavaScript 动态过滤 HTML 表的行 - dynamically filter rows of a HTML table using JavaScript 使用Javascript动态地将行添加到html表 - Dynamically adding rows to an html table, using Javascript 通过使用JavaScript在表中进行迭代来计算总价 - Calculating total price by iterating in the table using JavaScript 使用列选择器输入搜索 HTML 表,然后根据结果行显示属于该组的所有行 (Javascript) - Search An HTML Table Using A Column Selector Input And Then Display All The Rows That Are Part Of That Group Based On The Result Row (Javascript) 用For循环计算HTML表列总和的Javascript - Javascript calculating sum of a HTML table column with For loop 使用JavaScript代码将多行和多列动态插入html表中 - Insert multiple rows and columns to a table in html dynamically using javascript code 使用 Javascript 从 html 表中动态删除行 - Dynamically removing rows from an html table, using Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM