Javascript 如何获取刚刚点击的按钮用户的ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10291017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get ID of button user just clicked?
提问by Yang
Possible Duplicate:
Getting the ID of the element that fired an event using JQuery
可能的重复:
使用 JQuery 获取触发事件的元素的 ID
I have many buttons with ID attribute.
我有很多带有 ID 属性的按钮。
<button id="some_id1"></button>
<button id="some_id2"></button>
<button id="some_id3"></button>
<button id="some_id4"></button>
<button id="some_id5"></button>
Assume the user clicks on some button, and I want to alert this ID of the button the user just clicked on.
假设用户点击了某个按钮,我想提醒这个用户刚刚点击的按钮的 ID。
How can I do this via JavaScript or jQuery?
我怎样才能通过 JavaScript 或 jQuery 做到这一点?
I want to get the ID of button user just clicked.
我想获取刚刚单击的按钮用户的 ID。
回答by GeckoTang
$("button").click(function() {
alert(this.id); // or alert($(this).attr('id'));
});
回答by jlaceda
With pure javascript:
使用纯 javascript:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
回答by John Conde
You can also try this simple one-liner code. Just call the alertmethod on onclickattribute.
你也可以试试这个简单的单行代码。只需在onclick属性上调用警报方法。
<button id="some_id1" onclick="alert(this.id)"></button>
回答by Elliot Bonneville
$("button").click(function() {
alert(this.id);
});