#javascript #html
Вопрос:
Я действительно не знаю, что происходит, я недавно сделал это приложение flask и столкнулся с этой ошибкой, когда мои кнопки не работают для других строк таблицы html, которые там есть, и я не знаю, почему. Я изо всех сил старался решить эту проблему, но, к сожалению, не смог. Если кто-то может мне помочь, я был бы очень признателен
ВОТ HTML — КОД
<html lang="en">
<head>
<title>Timer</title>
<style>
body{
background-color: khaki;
}
h1{
font-family: monospace;
font-size:5em;
transform: translate(500px, 10px);
}
/*
h4{
font-family:monospace;
font-size: 2em;
transform: translate(700px, 10px);
} */
div.container input[type=submit] {
background-color:khaki;
border-radius: 1.8em 1.8em 1.8em;
text-transform: uppercase;
color: black;
border: none;
font-size: 2em;
font-family: monospace;
transform: translate(500px, 10px);
}
div.container input[type=text]{
transform: translate(500px, 10px);
}
table th{
text-align: left;
padding: 4px 8px;
transform: translate(500px, 10px);
}
table td{
/* background-color: aqua; */
border: 2px solid black;
padding: 4px 8px;
transform: translate(500px, 10px);
}
.btn{
background-size: 1em;
height: 2em;
width: 3em;
}
body{
margin: 0;
}
.draggable{
padding:1rem;
background-color: aliceblue;
border: 1px solid brown;
cursor: move;
}
.draggable.dragging{
opacity:0.5;
}
button.buttonReset{
color: black;
transform: scale3d(0.2, 0.2, 0.2);
}
.display{
font-family: monospace;
}
button.buttonPlay{
transform: translate(10px);
}
</style>
<link rel="shortcut-icon" href="{{url_for('static', filename='favicon.ico')}}">
</head>
<body>
<div class="container">
<h1>Task Manager</h1>
<br/>
<form action="/my_timers" method="POST">
<input type="text" placeholder="Enter New Task" name = "name" maxlength="10">
<input type="submit" value=" " class="btn btn-secondary" name="hello">
</form>
<br/><br/>
<table>
<tr>
<th>TASK</th>
<th> </th>
<th> </th>
<th>DONE</th>
<th>TIME TAKEN</th>
</tr>
</table>
{% for friend in friends%}
<table>
<tr>
<td>
<div class="container2">
<p class="draggable" draggable="true">
{{ friend.name }} <a href="/update/{{ friend.id }}" class="btn-outline-secondary btn-sm">Update</a>
</p>
</div>
</td>
</p>
</td>
<td>
<a href="/delete/{{ friend.id }}">
<button class="btn"> <img src="static/7bdd1bc7db7fd48025d4e39a0e2f0fd8.jpg" alt="button" width="20" height="20" ></button>
</a>
<a href="/description">
<button class="desbtn"> <button>
</a>
</td>
<td>
<div class="stopwatch">
<div class="circle">
<span class="time" id="display">00:00:00</span>
</div>
<div class="controls">
<img id="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg" />
<img id="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg" />
<img id="resetButton" src="/static/download.png" />
</div>
</div>
</td>
</tr>
</table>
<script src="static/new.js"></script>
<!-- <table>
<td>
{{ friend.name }}
</td>
</table> -->
{% endfor%}
</div>
</body>
</html>
А ВОТ И JS:
const timer = document.getElementById('circle');
var hr = 0;
var min = 0;
var sec = 0;
var stoptime = true;
function startTimer() {
if (stoptime == true) {
stoptime = false;
timerCycle();
}
}
function stopTimer() {
if (stoptime == false) {
stoptime = true;
}
}
function timerCycle() {
if (stoptime == false) {
sec = parseInt(sec);
min = parseInt(min);
hr = parseInt(hr);
sec = sec 1;
if (sec == 60) {
min = min 1;
sec = 0;
}
if (min == 60) {
hr = hr 1;
min = 0;
sec = 0;
}
if (sec < 10 || sec == 0) {
sec = '0' sec;
}
if (min < 10 || min == 0) {
min = '0' min;
}
if (hr < 10 || hr == 0) {
hr = '0' hr;
}
timer.innerHTML = hr ':' min ':' sec;
setTimeout("timerCycle()", 1000);
}
}
function resetTimer() {
timer.innerHTML = '00:00:00';
}
Кнопка воспроизведения, кнопка паузы, кнопка сброса не работают для любой другой задачи, которую я добавляю.
Пожалуйста, проверьте
Комментарии:
1. просто передайте имя функции, не отправляйте строку или timerCycle()
2. Но это все равно дает мне эту ошибку: Ошибка ссылки: стоптаймер не определен
Ответ №1:
Таким образом, вы не отслеживаете, какой таймер вы хотите воспроизвести.
Я знакомлю тебя с занятиями.
Я пытался сохранить большую часть вашего исходного кода нетронутым, но мне пришлось внести некоторые изменения.
Первое изменение, как я уже сказал, заключается в использовании классов. этот код создал объект таймера для каждого .timer
элемента, чтобы было легче отслеживать каждый отдельный таймер.
Второе изменение-добавление прослушивателей событий, поэтому нажатие на кнопки действительно что-то делает
Далее идет удаление sec = parseInt(sec);
. В этом нет необходимости, потому что вам не нужно отслеживать начальное значение 0 в этой переменной. Вы можете добавить его непосредственно перед отображением, например, в printTimer()
методе.
class Timer
{
timer = null;
hr = 0;
min = 0;
sec = 0;
stopTime = true;
constructor(timer) {
this.timer = timer;
this.setListeners();
}
setListeners = () => {
this.timer.querySelector('.playButton').addEventListener('click', this.startTimer);
this.timer.querySelector('.pauseButton').addEventListener('click', this.stopTimer);
this.timer.querySelector('.resetButton').addEventListener('click', () => {
this.stopTimer();
this.resetTimer();
});
}
startTimer = () => {
if (this.stopTime === true) {
this.stopTime = false;
this.timerCycle();
}
}
stopTimer = () => {
if (this.stopTime === false) {
this.stopTime = true;
}
}
resetTimer = () => {
this.hr = 0;
this.min = 0;
this.sec = 0;
this.printTimer();
}
timerCycle = () => {
if (this.stopTime === false) {
this.sec = 1;
if (this.sec === 60) {
this.min = 1;
this.sec = 0;
}
if (this.min === 60) {
this.hr = 1;
this.min = 0;
}
this.printTimer();
setTimeout(this.timerCycle, 1000);
}
}
printTimer = () => {
const displayHr = this.hr < 10 ? '0' this.hr : this.hr;
const displayMin = this.min < 10 ? '0' this.min : this.min;
const displaySec = this.sec < 10 ? '0' this.sec : this.sec;
this.timer.querySelector('.display').innerHTML = displayHr ':' displayMin ':' displaySec;
}
}
const timers = document.querySelectorAll('.timer');
timers.forEach(timer => {
new Timer(timer);
});
body {
background-color: khaki;
margin: 0;
}
button.buttonReset {
color: black;
transform: scale3d(0.2, 0.2, 0.2);
}
button.buttonPlay {
transform: translate(10px);
}
.display {
font-family: monospace;
}
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>
Комментарии:
1. Нет, вы не понимаете, проблема в том, что если я добавляю задачу в таблицу и засекаю время, она работает, но таймер запускается при первой задаче
2. Понял. Я обновил свой ответ. Надеюсь, это поможет.