使用JavaScript对多个按钮使用onclick

Using onclick with multiple buttons with JavaScript

本文关键字:onclick 按钮 JavaScript 使用      更新时间:2024-06-25

在我的长多页HTML文档中,我希望包含多个看起来相同、做同样事情的按钮(location.reload();)。出于不重复代码的想法,我想制作一个适用于所有代码的onclick事件。但我不知道怎么做。

我试着给他们提供相同的.class"reloadButton",而不是id,比如<button class="reloadButton">Reload</button>。然后我尝试使用var reload = documents.getElementsByClassName("reloadButton");

但我不知道该怎么办。尝试类似的东西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>