2 回答

TA貢獻1785條經驗 獲得超8個贊
我們沒有您的 html 標記,因此下面我剛剛創建了一個 ID 為“dPadRight”的 div 來添加偵聽器。然后我在 javascript 代碼的變量中引用了它。我假設您已經在做類似的事情來擁有一個名為“dPadRight”的變量。
根據您描述您需要“使用[計數器]做其他事情”的評論,我添加了另一個標識為“otherPad”的“pad”?!癲PadRight”可以用來增加計數器?!皁therPad”可以用來對計數器做一些事情。在下面的代碼中,我只是記錄它。
這里的教訓是,如果你想在計數器遞增之后使用它——好吧——那么你就不能在主要的 javascript 主體中引用它,因為那是在它有機會遞增之前。
let dPadRight = document.querySelector('#dPadRight');
let otherPad = document.querySelector('#otherPad');
let counter = 0;
dPadRight.addEventListener("click", () => {
counter++;
});
otherPad.addEventListener("click", () => {
console.log(counter);
});
<div id="dPadRight">
click to increment counter
</div>
<br/>
<div id="otherPad">
click to log counter
</div>

TA貢獻1802條經驗 獲得超5個贊
嘗試這個
let counter = 1;
let dPadRight = document.getElementById('dPadRight');
dPadRight.addEventListener("click", function() {
console.log(counter);
counter++;
if(counter > 5){
// just to show that counter is available outside the annonymous
// function
let bla = getCounterValue();
console.log("Bla Value " + bla);
}
}
);
function getCounterValue(){
return counter;
}
<button id="dPadRight">Increment Me </button>
添加回答
舉報