jQuery 如何在jQuery中检测当前元素ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8654716/
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 detect current element id in jQuery?
提问by Mohammad Saberi
I have some HTML codes:
我有一些 HTML 代码:
<input type="button" id="btn1" class="myButton" value="Button 1"/>
<input type="button" id="btn2" class="myButton" value="Button 2"/>
I need to run a jQuery function whenever user click each button, and I have to do it using their class.
每当用户单击每个按钮时,我都需要运行一个 jQuery 函数,并且我必须使用他们的类来执行此操作。
$('.myButton').click(function() {
// do something
});
But what I should to do, depends on the current element Id.
但是我应该做什么,取决于当前的元素 Id。
My question is that how can I detect which element called this function? I need to know its id.
我的问题是如何检测哪个元素调用了这个函数?我需要知道它的ID。
回答by Emre Erkan
You can use thisto access current element and then this.idwill give you the idof the current element.
您可以使用this来访问当前元素,然后this.id会给您id当前元素的 。
$('.myButton').click(function() {
alert(this.id);
});
回答by Armin
If you want to keep in jquery context, you could use this snippet:
如果你想保持在 jquery 上下文中,你可以使用这个片段:
$('.myButton').click(function() {
alert($(this).attr('id'));
});
With this way you are a bit more flexible.
通过这种方式,您会更加灵活。
回答by andreapier
回答by Jmunoz Dev
With jQuery i found this working:
使用 jQuery 我发现这个工作:
$(this).prop('id')
回答by Didier Ghys
thisin the event handler is the element that was clicked:
this在事件处理程序中是被点击的元素:
$('.myButton').click(function() {
if (this.id === "btn1") {
...
}
});

