我正在尝试创建一个应用程序,每次单击按钮都会创建一个新的秒表,其中包含一个 h1 和一个 div 元素:
const addButton = document.querySelector('.add-button')!;
addButton.addEventListener('click', createTimer);
function createTimer() {
var divTimer = document.createElement('div');
var divHeader = document.createElement('h1');
divHeader.textContent = 'Timer';
divTimer.textContent = '00:00:00';
document.body.appendChild(divHeader);
document.body.appendChild(divTimer);
}
但是,我想将通过按下上面的按钮创建的每个秒表的 DOM 元素与一个秒表对象相关联。这个想法是每个秒表都应该有自己的秒、分、小时。
const testTimerDisplay = document.getElementById('timerA')!;
//Class based objects ES6
class Stopwatch {
seconds: number;
minutes: number;
hours: number;
constructor() {
this.seconds = 0;
this.minutes = 0;
this.hours = 0;
}
tick() {
setInterval(() => {
this.seconds++
testTimerDisplay.textContent = this.seconds.toString(); //NOT A GOOD IMPLEMENTATION
}, 1000)
}
}
const timerA = new Timer();
如您所见,当我调用 tick() 时,它只会修改 testTimerDisplay,这当然不是我最终想要的。有没有办法让我点击按钮并将一个新的秒表对象与其创建的 DOM 相关联?
答案 0 :(得分:1)
好吧,您可以在 Stopwatch
结构中使用 ID:
// remove this:
// const testTimerDisplay = document.getElementById('timerA')!;
//Class based objects ES6
class Stopwatch {
// add the id prop
id: string,
seconds: number;
minutes: number;
hours: number;
// add id as a parameter for the constructor
constructor(id) {
this.id = id; // set the id
this.seconds = 0;
this.minutes = 0;
this.hours = 0;
}
tick() {
setInterval(() => {
this.seconds++;
// at tick method you increment display based on the id
const timerId = `timer${this.id}`;
const testTimerDisplay = document.getElementById(timerId);
testTimerDisplay.textContent = this.seconds.toString();
}, 1000)
}
}
现在您必须在 createTimer
函数中标记 id 时设置此 ID 字符串:
const addButton = document.querySelector('.add-button')!;
addButton.addEventListener('click', createTimer);
function createTimer() {
// first define this timer id, you could make it based on your list indexes
var id = document.getElementsByClassName('timer').length || 0;
var nextId = id + 1;
// then make a parent div that encapsulate the below tags
var parentDiv = document.createElement('div');
parentDiv.id = `timer${nextId}`;
parentDiv.className = 'timer';
var divTimer = document.createElement('div');
var divHeader = document.createElement('h1');
divHeader.textContent = 'Timer';
divTimer.textContent = '00:00:00';
parentDiv.appendChild(divHeader);
parentDiv.appendChild(divTimer);
document.body.appendChild(parentDiv);
}
因此,您创建了传递所需 ID 的秒表对象,该对象只会增加它自己的计时器:
var stopwatch1 = new Stopwatch('1');