如何使用javascript进行表格计算和迭代?

如何解决如何使用javascript进行表格计算和迭代?

背景: 我正在尝试学习JavaScript,因此决定尝试制作类似于电子表格的内容来学习循环。现在,我已经使用了一个月以上的时间,并且确实可以使用一些额外的帮助。由于我正在尝试学习Vanilla js,因此我试图避免其他任何事情。

到目前为止: 我发现用于计算行和整个表的解决方案不同,但是我觉得这些解决方案都不是很好。主要是我为此使用了for循环,但是引起了我的注意,foreach可能会更好,并且我正在尝试学习...所以现在我正在尝试理解嵌套的foreach循环。

问题: 由于我要使用表格中不同位置的每个单元格的数据,因此我需要弄清楚如何将每一行与其余行分开,然后分隔该特定行中的每个单元格(用于计算列)

解决方案: 正如我所说,我有一些奇怪的解决方案可用于计算行甚至整个表,但是它们并不能真正解决我的问题。我可能在这里错了一个想法,就是以某种方式使每一行都成为数组。
我知道以前曾经在这里问过类似的问题,并且我已经测试了其中的几个问题,但是我仍然很困惑。

我已经将所有代码放在下面的fiddlejs中。该表已设置为可按需更改。


非常感谢您提供任何帮助

https://jsfiddle.net/mpv0ds5g/1/

HTML:

<body>
    <div class="container">
      <!-- FORM 1 -->
      <form>
        <table>
          <caption>
            <strong>FIRST</strong>
          </caption>
          <tbody>
            <!-- ROW 0 -->
            <tr>
              <th scope="row">Row 0</th>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
            <!-- ROW 1 -->
            <tr>
              <th scope="row">Row 1</th>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <!-- FORM 2 -->
      <form>
        <table>
          <caption>
            <strong>SECOND</strong>
          </caption>
          <tbody>
            <!-- ROW 2 -->
            <tr>
              <th scope="row">Row 2</th>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
            <!-- ROW 3 -->
            <tr>
              <th scope="row">Row 3</th>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
            <!-- ROW 4 -->
            <tr>
              <th scope="row">Row 3</th>
              <td><output class="colsum output">0</output></td>
              <td><output class="colsum output">0</output></td>
              <td><output class="colsum output">0</output></td>
              <td><output class="colsum output">0</output></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <!-- FORM 3 -->
      <form>
        <table>
          <caption>
            <strong>THIRD</strong>
          </caption>
          <tbody>
            <!-- ROW 4 -->
            <tr>
              <th scope="row">Row 4</th>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
            <!-- ROW 5 -->
            <tr>
              <th scope="row">Row 5</th>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <!-- FORM 4 -->
      <form>
        <table>
          <caption>
            <strong>FOURTH</strong>
          </caption>
          <tbody>
            <!-- ROW 6 -->
            <tr>
              <th scope="row">Row 6</th>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><input type="number" value="0" /></td>
              <td><output></output></td>
            </tr>
            <!-- ROW 7 -->
            <tr>
              <th scope="row">Row 7</th>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output></output></td>
            </tr>
            <!-- ROW 8 -->
            <tr>
              <th scope="row">Row 8</th>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output></output></td>
            </tr>
            <!-- ROW 9 -->
            <tr>
              <th scope="row">Row 9</th>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output></output></td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <!-- FORM 5 -->
      <form>
        <table>
          <caption>
            <strong>FIFTH</strong>
          </caption>
          <tbody>
            <!-- ROW 10 -->
            <tr>
              <th scope="row">Row 10</th>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
            <!-- ROW 11 -->
            <tr>
              <th scope="row">Row 11</th>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
            <!-- ROW 12 -->
            <tr>
              <th scope="row">Row 12</th>
              <td><output class="editTable output output">0</output></td>
              <td><output class="editTable output output">0</output></td>
              <td><output class="editTable output output">0</output></td>
              <td><output class="editTable output output">0</output></td>
              <td><output class="rowsum output output">0</output></td>
            </tr>
            <!-- ROW 13 -->
            <tr>
              <th scope="row">Row 13</th>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="editTable output">0</output></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
            <!-- ROW 14 -->
            <tr>
              <th scope="row">Row 14</th>
              <td><output class="colsum output">0</output></td>
              <td><output class="colsum output">0</output></td>
              <td><output class="colsum output">0</output></td>
              <td><output class="colsum output">0</output></td>
              <td><output class="rowsum output">0</output></td>
            </tr>
          </tbody>
        </table>
      </form>
    </div>
    <script src="/app.js"></script>
  </body>

JS:

const forms = document.querySelectorAll("form");

forms.forEach(() => {
  f0 = forms[0];
  f1 = forms[1];
  f2 = forms[2];
  f3 = forms[3];
  f4 = forms[4];

  f0.onchange = editSheet;
  f1.onchange = editSheet;
  f2.onchange = editSheet;
  f3.onchange = editSheet;
  f4.onchange = editSheet;
});

function editSheet() {
  const body = document.querySelectorAll("tbody");
  const allrows = document.querySelectorAll("tr");
  const input = document.querySelectorAll("input");


// unwanted for-loop. Gets the job done,but returns html-error in the console
  for (i = 0; i < allrows.length; i++) {
    rowTotal = 0;
    for (ii = 0; ii < allrows[i].getElementsByTagName("input").length; ii++) {
      rowTotal =
        rowTotal + Number(allrows[i].getElementsByTagName("input")[ii].value);
    }
    allrows[i].querySelector(".rowsum").innerHTML = rowTotal;
  }

  /*
  body.forEach(() => {
    console.log(body[0]);
  }); // gives every <tbody>
  */

  /*
  allrows.forEach((i,ix) => {
    console.log(ix,i);
  }); // gives every <tr>
*/
  /*
  input.forEach((i,i.value);
  }); // gives every value in the cells
  */
}

解决方法

一些表格基础知识...

表中保留有“ ”和“ 单元格”这些保留字,以简化生活。

可以通过...访问单元格的内容

T.rows[x].cells[y].innerHTML

因此,要获取[行6,单元格4]的值,我们去...

var value = T.rows[6].cells[4].innerHTML; // "T" being the ID of the table.

我们要遍历一个表...

for(var x=0; x<T.rows.length; x++){

  T.rows[x].cells[3].innerHTML=5; // set the 3rd cell of every row to 5
}

现在,嵌套循环将遍历每个单元格...

for(var x=0; x<T.rows.length; x++){

 for(var y=0; y<T.cells.length; y++){

  T.rows[x].cells[y].innerHTML=0; // Initialise all cells with zero.

 }

}
,

第四个表没有rowsum类的元素。由于allrows[i].querySelector(".rowsum")返回null,因此会导致错误。反过来,这是因为没有rowsum元素要返回。

对于循环本身,可以用for调用来代替.forEach循环。

,

我会做一些不同的事情。我将不使用event.target遍历每个表单中的每一行,而是检测到哪个输入已更改,然后通过DOM“向上遍历”到父<tr>(通过{{ 1}}),然后从该元素中进行querySelect。

我认为代码是不言自明的。我在parentElement中添加了一些额外的变量,以使情况更加清楚。

我还更改了您的editSheet()循环,使它有点动态(无需更新代码即可添加或删除表单),并且代码更少。

forEach
const forms = document.querySelectorAll("form");

forms.forEach((formElement) => {
  formElement.onchange = editSheet;

/*  f0 = forms[0];
  f1 = forms[1];
  f2 = forms[2];
  f3 = forms[3];
  f4 = forms[4];

  f0.onchange = editSheet;
  f1.onchange = editSheet;
  f2.onchange = editSheet;
  f3.onchange = editSheet;
  f4.onchange = editSheet;*/
});

function editSheet(event) {
  const inputElement     = event.target;  // the input that sent the event
  const tableCellElement = inputElement.parentElement;      // td
  const tableRowElement  = tableCellElement.parentElement;  // tr
  
  const tableCellElements = tableRowElement.querySelectorAll('input');
  const outputElement     = tableRowElement.querySelector('output');
  
  let totalSum = 0;
  const DEFAULT_ZERO = 0;
  
  for (let i = 0; i < tableCellElements.length; i++) {
    totalSum += Number(tableCellElements[i].value) || DEFAULT_ZERO;
  }

  outputElement.value = totalSum;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res