简体   繁体   English

如何获得 function 中被点击的数字的总和?

[英]How can I get the sum of numbers being clicked in function?

I keep receiving just the new number, no sum.我一直收到新号码,没有金额。 While I see what the problem is- I'm unable to figure out how to fix it.虽然我看到了问题所在 - 我无法弄清楚如何解决它。 This is my code:这是我的代码:

<script>
  let temp = `<Table border = 1>`;
  for (let row = 1; row <= 10; row++) {
    temp += `<tr>`;
    for (let cols = 1; cols <= 10; cols++) {
      temp += `<td style='(${row * cols},
                 ${row * cols}, ${row * cols})'> ${row * cols} </td>`;
    }
  }
  temp += "</Tr>";
  temp += `</table> `;
  multiBoard.innerHTML = temp;

  function sumNums() {
    let sum = event.target.innerText;
    let saveSum = "";
    saveSum += sum;
    console.log(saveSum);
  }
</script>

A few things:一些东西:

  1. You declare saveSum as a string when it should be an integer.saveSum应该是 integer 时,您将其声明为字符串。 Change it to let saveSum = 0;将其更改为let saveSum = 0;
  2. You should declare the saveSum variable globally (outside of the sumNums function)您应该全局声明saveSum变量(在sumNums函数之外)
  3. I assume you're calling the function from HTML, but if not that needs to be addressed as well.我假设您从 HTML 调用 function,但如果不是,也需要解决。
  4. Update the sum declaration to let sum = parseInt(event.target.innerText);更新sum声明let sum = parseInt(event.target.innerText); to make sure you're performing addition rather than string concatenation.以确保您执行的是加法而不是字符串连接。

Try this.尝试这个。

<script>
  let temp = `<Table border = 1>`;
  let saveSum = 0;
  for (let row = 1; row <= 10; row++) {
    temp += `<tr>`;
    for (let cols = 1; cols <= 10; cols++) {
      temp += `<td style='(${row * cols},
                 ${row * cols}, ${row * cols})'> ${row * cols} </td>`;
    }
  }
  temp += "</Tr>";
  temp += `</table> `;
  multiBoard.innerHTML = temp;

  function sumNums() {
    let sum = event.target.innerText;
    saveSum += Number(sum);
    console.log(saveSum);
  }
</script>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM