简体   繁体   English

如何在没有 onclick 事件的情况下注册单击按钮?

[英]how to register click on a button without onclick event?

I have like 30 or so buttons in my react app.我的反应应用程序中有大约 30 个按钮。 and i don't want to add event-Listener to each and every button.而且我不想为每个按钮添加事件侦听器。 but every button has a specific job to do.但每个按钮都有特定的工作要做。 So is there any way i can achieve this.那么有什么方法可以实现这一点。

something like this(its depreciated now):像这样的东西(现在已经贬值了):

$("button").click(() => {
    fetch("https://reqres.in/api/users/" + this.value)
      .then((res) => res.json())
      .then((result) => setUser(result));
  });

I added the same class names to DOM elements which you want to add the event listeners and those elements by using getElementsByClassNames method.我使用 getElementsByClassNames 方法将相同的类名添加到要添加事件侦听器和那些元素的 DOM 元素中。 Then, added the event listener to them.然后,将事件侦听器添加到它们。

 let count = 0; function onClick() { document.getElementById("count").innerText = count++; } const buttons = document.getElementsByClassName("btn-multiple"); [...buttons].forEach(btn => btn.addEventListener("click", onClick));
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Simple scroll example</title> <style> </style> </head> <body> <section id="clear-section" class="clear-section"> <input type="button" value="V1" class="btn-multiple" /> <input type="button" value="V2" class="btn-multiple" /> <input type="button" value="V3" class="btn-multiple" /> <input type="button" value="V4" class="btn-multiple" /> <input type="button" value="V5" class="btn-multiple" /> <input type="button" value="V6" class="btn-multiple" /> <p id="count"></p> </section> </body> </html>

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

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