Javascript获取DOM元素的索引

时间:2018-09-14 10:47:14

标签: javascript dom

能帮我找到单击DOM按钮的ID的方法

out=document.getElementsByClassName("mybutton")
HTMLCollection(2) [button.mybutton, button.mybutton]
0
:
button.mybutton
1
:
button.mybutton
length
:
2
__proto__
:
HTMLCollection

2 个答案:

答案 0 :(得分:1)

使用buttonElement.addEventListener('click', clickHandlerFunction);向按钮添加点击处理程序。

function onMyButtonClick(clickEvent) {
  var button = clickEvent.target;
  console.log('ID of clicked button: ' + button.id);
}

document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('.mybutton').forEach(function (button) {
    button.addEventListener('click', onMyButtonClick);
  })
});
<button id="button-1" class="mybutton" type="button">Button 1</button>
<button id="button-2" class="mybutton" type="button">Button 2</button>

答案 1 :(得分:0)

如果您的按钮看起来像这样,

<button type="button" id="save" class="button">Save</button>
<button type="button" id="cancel" class="button">Cancel</button>

您可以监听按钮上的点击事件,并使用event.target.id

获取其ID。
function handleClick(event) {
  console.log(event.target.id);  // prints the id of the clicked button
}

document.querySelectorAll(".button").forEach(function(button) { 
  button.addEventListener('click', handleClick);
});

ES6方法:

const buttons = document.querySelectorAll(".button");
Array.from(buttons, button => button.addEventListener('click', () => {
    console.log(button.id) // prints the id of the clicked button
}));