Вызов element.onclick
Всем привет. У меня есть готовый рабочий код таймера обратного отсчета. Передо мной стоит задача, добавить конструктор и передать туда ID кнопок. С помощью этих ID вызывать при клике (element.onclick) в самом javascript файле. Но у меня что-то не работает, не могу найти ошибку. Раньше Onclick был в Html файле как атрибут элемента, но теперь нужно это сделать при помощи javascript.
Заранее благодарю за помощь. :) Вот JS class Timer { constructor(id1, id2) { this.idStart = id1; this.idReset = id2; document.getElementById(this.idStart).onclick = this.start(); document.getElementById(this.idReset).onclick = this.resetTimer(); } countDown() { this.s--; if (this.s < 0) { this.s = 59; this.m--; } if (this.m < 0) { this.m = 59; } if (this.s + this.m == 0) { resetTimer(); } this.s = this.s + ""; this.m = this.m + ""; if (this.s.length < 2) { this.s = "0" + this.s; } if (this.m.length < 2) { this.m = "0" + this.m; } document.getElementById("tm").innerHTML = this.m + ":" + this.s; } resetTimer(){ clearInterval(this.timerId); this.m = 0; this.s = 0; document.getElementById("tm").innerHTML = '00' + ':' + '00'; document.getElementById("minutes").value = ""; document.getElementById("minutes").removeAttribute("disabled", ""); this.status = 0; } start(){ document.getElementById("minutes").setAttribute("disabled", ""); this.m = +document.getElementById("minutes").value; this.s = 0; this.status = 0; this.timerId; if(!this.status){ this.status = 1; this.timerId = setInterval(this.countDown.bind(this), 1000); } } } Вот код HTML <!DOCTYPE html> <html> <head> <title>Timer</title> <meta charset="UTF-8"> <link rel="stylesheet" href="newcss.css"> <link rel="shortcut icon" href="#"> </head> <body> <div id="tm">00:00</div> <label>Write minutes</label><br> <input type="number" id="minutes"> <input type="button" value="Start" id="start-button"> <input type="button" value="Reset" id="reset-button"> <script type="text/javascript" src="newjavascript.js"></script> <script> var timer = new Timer("start-button", "reset-button"); </script> </body> </html> |
Цитата:
Цитата:
Строки 6-7 должны быть такими: document.getElementById(this.idStart).onclick = this.start.bind(this); document.getElementById(this.idReset).onclick = this.resetTimer.bind(this); Еще можно сохранять не ID контроллов, а ссылки на них самих, в этом случае не придется каждый раз их искать. |
Цитата:
|
Часовой пояс GMT +3, время: 09:50. |