You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义递增步长的JavaScript计数器无法累加问题求助

Fixing Your Custom Step Counter Issue

Hey Sean, glad you already nailed down the root cause! Let me break this down more clearly and show you how to implement the fix properly, plus some extra tips to polish things up.

The core problem here is that your counter variable was declared inside the myFunction() function. Every time you clicked the button, the function would run from scratch, and var counter = 0; would reset the value to 0 before adding 3 or 5. That’s why you never saw an accumulated total—you were always starting over!

Corrected Code

Here’s the adjusted version that maintains the counter’s value between clicks:

<body>
  <div class="question">
    <script>
      // Declare counter outside the function so it persists between button clicks
      let counter = 0;

      function myFunction() {
        const userAnswerRaw = document.getElementById("uAnswer").value;
        const userAnswer = userAnswerRaw.toUpperCase();
        document.getElementById("test").innerHTML = userAnswer;

        switch(userAnswer){
          case "YES":
            counter += 3;
            document.getElementById("counterDisplay").innerHTML = counter;
            break;
          case "NO":
            counter += 5;
            document.getElementById("counterDisplay").innerHTML = counter;
            break;
          default:
            alert("You need to input either Yes or No!")
            break;
        }
        // Optional: Clear the input field after submission for better UX
        document.getElementById("uAnswer").value = "";
      }
    </script>
    <h1>Questions</h1>
    <p id="test"></p>
    <p id="counterDisplay"></p>
    <button onclick="myFunction()">Click</button>
    <input type="text" id="uAnswer">
  </div>
</body>

Key Details to Note

  • Variable Scope: Moving let counter = 0; outside the function makes it scoped to the entire <script> block (instead of being recreated every time the function runs). This lets it retain its value between button clicks, so each addition builds on the previous total.
  • let vs var: I swapped var for let here—modern JavaScript prefers let because it has predictable block scoping and avoids weird hoisting quirks that var can introduce.
  • UX Polish: I added a line to clear the input field after each submission, which makes the tool feel more intuitive to use.

Bonus: Avoiding Global Variables (Best Practice for Larger Projects)

If you want to keep your counter private and avoid cluttering the global scope (a good habit for bigger codebases), you can use a closure to encapsulate the counter:

const myFunction = (() => {
  let counter = 0; // This counter is private to the closure
  return () => {
    const userAnswerRaw = document.getElementById("uAnswer").value;
    const userAnswer = userAnswerRaw.toUpperCase();
    document.getElementById("test").innerHTML = userAnswer;

    switch(userAnswer){
      case "YES":
        counter += 3;
        document.getElementById("counterDisplay").innerHTML = counter;
        break;
      case "NO":
        counter += 5;
        document.getElementById("counterDisplay").innerHTML = counter;
        break;
      default:
        alert("You need to input either Yes or No!")
        break;
    }
    document.getElementById("uAnswer").value = "";
  };
})();

This way, counter can’t be accidentally modified by other parts of your code, keeping your logic clean and safe.

内容的提问来源于stack exchange,提问作者Sean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:49:11