-2

我是 JS 新手。我在第 2 行需要帮助...单击按钮时如何获取自变量的值?基本上 var i 每 100 毫秒递增一次,我想在单击按钮时捕获它的值。非常感谢!

    function startGame(){
    **var clickValue = thebutton.addEventListener()** // I need this variable to capture to value of **i** when thebutton is clicked
    var i = -50
    var timer = setInterval(timerActual, 100);
    function timerActual(){
        console.log(i)
        i++;
        if (i===600) {
            clearInterval(timer)
        }
    }}
4

1 回答 1

0

您可以在事件侦听器函数中访问该变量。

function startGame() {
  var i = -50
  let thebutton = document.querySelector("#button");
  thebutton.addEventListener('click', function() {
    console.log(`i = ${i}`);
  });
  var timer = setInterval(timerActual, 100);

  function timerActual() {
    i++;
    if (i === 600) {
      clearInterval(timer)
    }
  }
}

document.querySelector("#start").addEventListener("click", startGame);
<button id="start">Start</button>
<button id="button">See timer</button>

于 2021-03-23T02:10:22.350 回答