你能帮我找到点击DOM按钮的id的方法吗?
out=document.getElementsByClassName("mybutton")
HTMLCollection(2) [button.mybutton, button.mybutton]
0
:
button.mybutton
1
:
button.mybutton
length
:
2
__proto__
:
HTMLCollection
使用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>
如果你的按钮看起来像这样,
<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
}));
HTML:
<button class="mybutton" id ="one">1</button>
<button class="mybutton" id="two">2</button>
<button class="mybutton" id="three">3</button>
JavaScript的:
let myButtons = document.getElementsByClassName("mybutton");
for (let i = 0; i < myButtons.length; i++) {
myButtons[i].addEventListener("click", function(event) {
event.preventDefault();
console.log(this.getAttribute("id"));
});
}
我们也可以使用forEach方法,但因为document.getElementsByClassName返回一个HTMLCollection而不是一个数组,ES6 Array.from()或spread从类似数组的对象构建数组,我们可以使用forEach方法迭代HTMLColection对象。更多细节在here
[...myButtons].forEach(function(button) {
button.addEventListener("click", function(event) {
event.preventDefault();
console.log(this.getAttribute("id"));
});
});
或者,您可以使用返回NodeList而不是document.getElementsByClassName()的document.querySelectorAll()。
let myButtons = document.querySelectorAll(".mybutton");
myButtons.forEach(function(button) {
button.addEventListener("click", function(event) {
event.preventDefault();
console.log(this.getAttribute("id"));
});
});
只需使用for循环,然后检查该元素的属性:
<button onClick="buttonClick($event)" id="something1" class="mybutton"></button>
<button id="something2" class="mybutton"></button>
<button id="something3" class="mybutton"></button>
function buttonClick(event) {
for(var i = 0; i < out.length; i++) {
if (event.target.attribute[0] === out[i].attributes[0].value){
do something}
}
}
这是你需要检查的东西,但单独点击功能,事件将检查点击了哪个按钮。