📌  相关文章
📜  将函数应用于具有类名的所有元素 - TypeScript 代码示例

📅  最后修改于: 2022-03-11 14:48:33.049000             🧑  作者: Mango

代码示例1
/*
The getElementsByClassName returns a array of elements (2 in your example),
so you'll have to loop through it and add the onclick event.
To access the current button inside the onclick event handler, use this.
You cannot pass whatever parameters you want to the function because its signature is fixed.
It gets passed a reference to the event itself, not the clicked element,
so the name clicked_button is deceiving. We usually call that parameter event,
or e for short. You can access the element using event.target, but using this is just easier.

*/

var value;
var buttons = document.getElementsByClassName('button');

for (var i = 0; i < buttons.length; i++) {
  buttons[i].onclick = selectValue;
}

function selectValue() {
  value = this.value;
  console.log(value);
}