如何在函数中使用变量的最新值[重复]

问题描述 投票:0回答:2

我有一段重要的代码。函数showResultAndCount()显示counter并添加1,另一个函数showResult()只显示counter

我希望这两个函数能够使用变量counter的最新值。目前这两个函数似乎都有自己的变量版本。如何在不使用全局变量的情况下实现此目的?

这么基本我认为这将是一个重复,但我不知道如何调用此行为,因此不知道我应该在堆栈溢出或谷歌上搜索什么。

<script>
  function showResultAndCount(counter) {
    let someButton = document.getElementById('counter1');
    someButton.addEventListener('click', function() {
      counter++;
      alert(counter);
    });
    return counter;
  }

  function showResult(counter) {
    someButton = document.getElementById('counter2');
    someButton.addEventListener('click', function() {
      alert(counter);
    });
  }
</script>

<button id='counter1'>
  Show counter and count
</button>
<br /><hr />
<button id='counter2'>
  Show counter
</button>

<script>
  let counter = '0';
  counter = showResultAndCount(counter);
  showResult(counter);
</script>
javascript
2个回答
1
投票

这应该做......

注意:不污染全局命名空间因此确定范围是一个好习惯。

(function(){
  let counter = 0;
  
  function showResultAndCount() {
   let someButton = document.getElementById('counter1');
   someButton.addEventListener('click', function() {
     counter++;
     alert(counter);
   });
  }

  function showResult() {
    someButton = document.getElementById('counter2');
    someButton.addEventListener('click', function() {
      alert(counter);
    });
  }
  
  showResultAndCount();
  showResult();
  
})();
<button id='counter1'>
  click this text to show the counter and count
</button>
<br /><hr />
<button id='counter2'>
  click this text to show the counter
</button>

1
投票

请尝试以下操作 - 不要在函数中传递counter变量,方法是创建变量的单独副本。

<script>
  function showResultAndCount() {
    let someButton = document.getElementById('counter1');
    someButton.addEventListener('click', function() {
      counter++;
      alert(counter);
    });
  }

  function showResult() {
    someButton = document.getElementById('counter2');
    someButton.addEventListener('click', function() {
      alert(counter);
    });
  }
</script>

<button id='counter1'>
  click this text to show the counter and count
</button>
<br /><hr />
<button id='counter2'>
  click this text to show the counter
</button>

<script>
  let counter = 0;
  showResultAndCount();
  showResult();
</script>
© www.soinside.com 2019 - 2024. All rights reserved.