简体   繁体   English

我必须双击跟随按钮才能运行这是由于使用了 click 事件 2 次

[英]I have to double click the follow button to functioning this is due to using click event 2 time

I am working on follow button and with the help of JavaScript I've come up with the following code.我正在研究关注按钮,在 JavaScript 的帮助下,我想出了以下代码。

But the problem is I have to double click the follow button to functioning this is due to using click event 2 time.但问题是我必须双击跟随按钮才能运行这是由于使用了 click 事件 2 次。 I am open to better methods of solving this too.我也愿意接受更好的方法来解决这个问题。

 var value = null; const onClick = (event) => { // event.target.id value = event.target.id; console.log(value); document.getElementById(`${value}`).addEventListener('click',function(){ // console.log(value.id); if(this.classList.contains('follow')){ this.classList.remove('follow'); this.innerHTML ="Following"; this.style.backgroundColor = 'green'; }else{ this.classList.add('follow'); this.style.backgroundColor = 'rgb(27,18,83)'; this.innerHTML="Follow"; } }) } window.addEventListener('click', onClick);

There is a double click event.有一个双击事件。 You can check the if it satisfies your requirement.您可以检查它是否满足您的要求。

MDN link - https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event MDN 链接 - https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event

For multiple buttons with the same function, I would give all of them the same class (eg "btn").对于具有相同 function 的多个按钮,我会给它们所有相同的 class(例如“btn”)。 Then in JS simply get all of the elements with this class, loop over the HTMLCollection which you would get and assign each element an eventlistener.然后在 JS 中只需使用这个 class 获取所有元素,循环遍历您将获取的 HTMLCollection 并为每个元素分配一个事件监听器。 When you want to change something on the button you have to use event.target in the function:当您想更改按钮上的某些内容时,您必须在 function 中使用event.target

 let buttons = document.getElementsByClassName("btn"); for (btn of buttons) { btn.addEventListener("click", (event) => { if(event.target.classList.contains('follow')){ event.target.classList.remove('follow'); event.target.innerHTML ="Following"; event.target.style.backgroundColor = 'green'; }else{ event.target.classList.add('follow'); event.target.style.backgroundColor = 'rgb(27,18,83)'; event.target.innerHTML="Follow"; } }); }
 <button class="btn">1</button> <button class="btn">2</button>

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

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