繁体   English   中英

使用带有 JavaScript 的多个按钮的 onclick

[英]Using onclick with multiple buttons with JavaScript

在我的长、多页 HTML 文档中,我想包含多个看起来相同并执行相同操作的按钮 (location.reload();)。 出于不重复代码的想法,我想制作一个适用于所有人的 onclick 事件。 但我无法弄清楚如何。

我试过给他们所有相同的 .class “reloadButton” 而不是 id,例如<button class="reloadButton">Reload</button> 然后我尝试使用var reload = documents.getElementsByClassName("reloadButton"); .

但我不知道从那里做什么。 尝试类似reload.onclick = function () { location.reload(); } reload.onclick = function () { location.reload(); }似乎不起作用。

当它附加到 onclick 事件时,我不确定如何使用 for 循环来遍历所有类似数组的 HTMLCollection。

这只是纯 JavaScript,我的专业水平也是纯初学者。 所以,如果你能在脑海中解释它,或者如果你能链接一个网站,在我可能能够理解的水平上解释这一点,我会喜欢它。 谢谢!

更新版本

window.addEventListener("load", function() { // when the page has loaded
  document.getElementById("NearestStaticContainerForButtons").addEventListener("click", function(e) {
    const tgt = e.target;
    if (tgt.classList.contains("reloadButton")) {
      e.preventDefault(); // stop the button if not type=button 
      location.reload();
    }
  });
});

旧版本

普通JS:

window.onload=function() { // when the page has loaded
  var bt = document.querySelectorAll(".reloadButton"); // get all buttons with the class
  for (var i=0;i<bt.length;i++) { // newer browsers can use forEach
    bt[i].onclick=function() { // assign anonymous handler
      location.reload();
    }
  }
}

或使用命名函数

function reloadPage() {
  location.reload();
}
window.onload=function() { // when the page has loaded
  var bt = document.querySelectorAll(".reloadButton"); // get all buttons with the class
  for (var i=0;i<bt.length;i++) { // newer browsers can use forEach
    bt[i].onclick=reloadPage;
  }
}

 var buttons = document.querySelectorAll('.js-say-hi'); var displayBox = document.querySelector('.js-display-greeting'); // wire displayGreeting function to each button with .js-say-hi class for (var i=0; i<buttons.length; i++) { buttons[i].addEventListener('click', displayGreeting) } function displayGreeting(event) { var buttonNumber = event.target.textContent[event.target.textContent.length - 1]; displayBox.textContent += 'hello from button ' + buttonNumber + '! '; }
 <button class="js-say-hi">Say hi 1</button> <button class="js-say-hi">Say hi 2</button> <button class="js-say-hi">Say hi 3</button> <button class="js-say-hi">Say hi 4</button> <button class="js-say-hi">Say hi 5</button> <div class="js-display-greeting"></div>

你也可以只使用命名函数

function reloadPage() {
  location.reload();
}

然后代替

<button class="reloadButton">Reload</button>

使用

<button onclick="reloadpage();">Reload</button>

暂无
暂无

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

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