简体   繁体   English

Javascript 事件监听器“e”

[英]Javascript event listener "e"

I'm trying to get a grasp of e, this, binding.我试图掌握 e,this,binding。 In this example, if you press the create new div button you get an elapsed time and start button.在这个例子中,如果你按下创建新的 div 按钮,你会得到一个经过时间和开始按钮。 If you create multiple divs and press start on each, they are all impacted.如果您创建多个 div 并在每个上按 start,它们都会受到影响。 I'm trying to make the elapsed time correspond to the button that was clicked.我正在尝试使经过的时间与单击的按钮相对应。 I passed in "e" through out the functions but I'm not sure how to handle the next step.我通过函数传递了“e”,但我不确定如何处理下一步。

QUESTION: Should I add let clickedButton = event.target or event.parent within the start timer function and then in the display time, would that be clickedButton.newP.innerHTML = hour_format + " :" + min_format +" : " + sec_format;问题:我是否应该在开始计时器函数中添加 let clickedButton = event.target 或 event.parent,然后在显示时间中添加 clickedButton.newP.innerHTML = hour_format + " :" + min_format +" : " + sec_format; } }

Below is the code:下面是代码:

 //"create div" button with click events let initial = document.getElementById("test"); initial.addEventListener("click", newPElement); let myTextArea = document.getElementById("textArea"); let newP; //function that creates a P function newPElement(){ newP = document.createElement("p"); newP.classList.add("myFont"); newP.innerHTML = "00:00:00"; myTextArea.appendChild(newP); let start = document.createElement("button"); start.innerText = "START"; start.addEventListener("click",function(e){ timer = setInterval(startTimer, 1000) }) myTextArea.appendChild(start); } function startTimer(e) { sec++; if(sec === 60){ sec === 0 min++; } if (min === 60){ min === 0; hour++; } displayTime(e) } //Global variables for the timer function let timer; let sec = 0; let min = 0; let hour = 0 let newElapsedTime; function displayTime(e){ let sec_format = sec; let min_format = min; let hour_format = hour; if(sec < 10){ sec_format = "0"+sec; } if(min < 10){ min_format = "0"+min; } if (hour <10){ hour_format = "0"+hour; } newP.innerHTML = hour_format + " :" + min_format +" : " + sec_format; }
 <h1>Testing</h1> <button id="test" class="test">CREATE DIV</button> <section id="textArea"> </section>

You seem to have some scoping issues here: the variables newP and sec , min , hour are on the global scope.您似乎在这里有一些范围界定问题:变量newPsecminhour都在全局范围内。 You only have one instance of sec , min and hour , which means that it is impossible to keep track of the different timers that you create.您只有一个secminhour实例,这意味着无法跟踪您创建的不同计时器。 Also, every time you create a new timer, you update newP to point to that new element, so the old ones are "forgotten".此外,每次创建新计时器时,都会更新newP以指向该新元素,因此旧的将被“遗忘”。 Because of this, only the value of the most recent timer will be updated.因此,只会更新最近的计时器的值。

I would highly recommend utilizing const instead of let whenever it makes sense to do so.我强烈建议在有意义的时候使用const而不是let The value of a const variable can't be changed, so it will guard you against accidentally changing a value that you didn't mean to change. const变量的值无法更改,因此它可以防止您意外更改您无意更改的值。 For example, making the newP variable a const might alert you to the fact that you're trying to reassign the value of the existing variable to a new timer element instead of creating a new variable that would be independent of the old one.例如,将newP变量设置为const可能会提醒您,您正在尝试将现有变量的值重新分配给新的计时器元素,而不是创建一个独立于旧变量的新变量。 I think that DOM elements are a great example of something that should (or at least could) almost always be a const , since usually you want them to point to the same element that you originally intended to target.我认为 DOM 元素是一个很好的例子,它应该(或至少可以)几乎总是一个const ,因为通常你希望它们指向你最初打算定位的同一个元素。 Note that you can still change the element's attributes, such as innerText , you just can't change the DOM element that it points to, or change the variable into to an integer or something.请注意,您仍然可以更改元素的属性,例如innerText ,您不能更改它指向的 DOM 元素,或者将变量更改为整数或其他内容。 Of course it's mostly a matter of personal preference, but I've found that for me it makes it much easier to debug things like this.当然,这主要是个人喜好问题,但我发现对我来说,调试这样的事情要容易得多。

Also, the timer in your example doesn't seem to work as intended.此外,您示例中的计时器似乎没有按预期工作。 Here's my quick take on this sort of feature, let me know if there's anything you want to ask about it!这是我对此类功能的快速介绍,如果您有任何问题,请告诉我!

 const timerContainer = document.querySelector('#timers') const addTimerButton = document.querySelector('#add-timer') // Note that all the new elements are scoped inside the function that gets triggered by this eventListener addTimerButton.addEventListener('click', () => { // Create the new timer and start button const timer = document.createElement('p') const startButton = document.createElement('button') startButton.innerText = 'Start' // Set elapsedSeconds to 0 and initialize the timer's value let elapsedSeconds = 0 updateTimerValue() // Add the newly created elements to the timerContainer timerContainer.append(startButton, timer) // Start the timer startButton.addEventListener('click', () => { // Increment the timer every second and update the timer's text value setInterval(() => { elapsedSeconds++ updateTimerValue() }, 1000) }) function updateTimerValue() { // Count the seconds, minutes and hours, convert to strings and pad the strings with leading 0's const seconds = String(elapsedSeconds % 60).padStart(2, '0') const minutes = String(parseInt(elapsedSeconds / 60 % 60)).padStart(2, '0') const hours = String(parseInt(elapsedSeconds / 60 / 60)).padStart(2, '0') // Use string interpolation for formatting the timer string timer.innerText = `${hours}:${minutes}:${seconds}` } })
 p { margin-block: 0.2rem 0.6rem } button { padding: 0.2rem 0.7rem; cursor: pointer; }
 <button id="add-timer" type="button">Add new timer</button> <hr> <div id="timers"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM