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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:42:21  来源:igfitidea点击:

How to get ID of button user just clicked?

javascriptjqueryhtml

提问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);
    };
}?

http://jsfiddle.net/TKKBV/2/

http://jsfiddle.net/TKKBV/2/

回答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);
});