我正在構建一個帶有多個計時器的頁面。當用戶單擊按鈕時,將創建計時器。因此,假設用戶單擊“K Timer 1”按鈕。JS 創建了一個我想參考為“KT1”或 timers['KT1'] 的新計時器。
這是我正在嘗試的方式,你們 JS 窺視者現在可能正在嘲笑我的解決方案。沒關系。我更喜歡 PHP。
HTML
<button type="button"
onClick="newUTimer('KT1');">
Timer 1
</button>
<button type="button"
onClick="newUTimer('KT2');">
Timer 2
</button>
JS - 舊有錯誤
var timers = {};
newUTimer=function(id){
// If timer does not exist, create it
if (!globalThis.timers.[id]){
globalThis.timers.[id] = new CUTimer(id);
globalThis.timers.[id].starter();
// If there is already a timer with that ID, reset it
}else{
globalThis.timers.[id].reset();
}
}
我需要跟蹤計時器的原因是,我可以在用戶第二次單擊按鈕時重置計時器,而不是創建另一個沖突的計時器。
JS - 更新和作業,但不確定這是我應該這樣做的正確方法。
var timers = {};
newUTimer=function(id){
// If timer does not exist, create it
if (!globalThis.timers[id]){
globalThis.timers[id] = new CUTimer(id);
globalThis.timers[id].starter();
// If there is already a timer with that ID, reset it
}else{
// Call object resetIt method
globalThis.timers[id].resetIt();
}
}
uj5u.com熱心網友回復:
丟失陣列括號前的點:
globalThis.timers.[id].starter()應該是globalThis.timers[id].starter()
uj5u.com熱心網友回復:
您應該接受aPajos 答案,因為它指出了您的實際錯誤。至于“更正確的方法”,擺脫行內javascript
var timers = {};
/*Get the buttons with the data attributes*/
let timerButtons = document.querySelectorAll("button[data-timerid]");
/*Itterate them adding an event handler*/
timerButtons.forEach(function(item){
item.addEventListener("click", function(){
/*Get the id from the data atttribute*/
let timerId = this.dataset.timerid;
/*Better to go the positive case first*/
if(timers[timerId]){
timers[timerId].resetIt();
}else{
timers[timerId] = new CUTimer(timerId);
}
});
})
function CUTimer(id){
this.id = id;
this.starter = function(){console.log("Starting : " this.id)};
this.resetIt = function(){console.log("Resetting : " this.id)};
//Call your starter method in the construtor
this.starter();
};
<!-- Use Data Attributes to store the timer Id -->
<button type="button" data-timerid='KT1'>Timer 1</button>
<button type="button" data-timerid='KT2'>Timer 2</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425527.html
標籤:javascript 哎呀
