如何将 1 添加到 JavaScript 变量而不减少它的原始数字?

我想增加 1 个变量而不减少原始数字的任何内容。比如说我从 10 而不是 0 开始,我如何让它去 11 而不是重置。


例子:


<div class="game-object">

  <script type="text/javascript">

    var clicks = 0;


    function updateClickCount() {

      document.getElementById("clickCount").innerHTML = clicks;

    }

  </script>

  <button type="button" onClick="clicks++;updateClickCount();" id="push">NO.</button>

  <div id="clickCount"></div>

</div>


蛊毒传说
浏览 145回答 1
1回答

MM们

您可以使用 localstorage 来存储上次点击次数,它也会在页面重新加载时保持不变。尝试这个。<header>&nbsp; &nbsp; <strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Don't Touch The Button&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </strong></header><div class="game-object">&nbsp; &nbsp; <script type="text/javascript">&nbsp; &nbsp; &nbsp; &nbsp; let localData = localStorage.getItem('clicks');&nbsp; &nbsp; &nbsp; &nbsp; var clicks = 0;&nbsp; &nbsp; &nbsp; &nbsp; if (localData) clicks = Number(localData)&nbsp; &nbsp; &nbsp; &nbsp; function updateClickCount() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clicks++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; localStorage.setItem('clicks', clicks);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("clickCount").innerHTML = clicks;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script>&nbsp; &nbsp; <button type="button" onClick="updateClickCount();" id="push">NO.</button>&nbsp; &nbsp; <div id="clickCount"></div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript