jQuery jQuery按类查找单击按钮的ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4938876/
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
jQuery find ID of clicked button by class
提问by benhowdle89
I have numerous buttons on my page with the same class names. However these buttons have different ID's. How do i do this:
我的页面上有许多具有相同类名的按钮。但是,这些按钮具有不同的 ID。我该怎么做呢:
$(".vote").click(function(){
var id = $(this).{ID OF CLICKED BUTTON};
});
How can i make this pseudo code work?
我怎样才能使这个伪代码工作?
Thanks
谢谢
回答by user113716
$(".vote").click(function(){
var id = this.id;
});
The ID is accessible directly from the element. There's absolutely no need to use a jQuery method.
ID 可直接从元素访问。绝对不需要使用 jQuery 方法。
回答by simshaun
With jQuery object (not necessary)
使用 jQuery 对象(不是必需的)
$(".vote").click(function(){
var id = $(this).attr('id');
});
Without jQuery object (faster)
没有 jQuery 对象(更快)
$(".vote").click(function(){
var id = this.id;
});
回答by Sk Asraf
i think this also work
我认为这也有效
$("body").on("click",".vote",function(){
var id = this.id;
});
回答by user9160528
Use this code
使用此代码
$(document).on('click','.vote',(event)=>{
var id = $(event.target).attr('id');
})
M sure you never face any problem with this solution in any situation.
我相信您在任何情况下都不会遇到此解决方案的任何问题。
回答by Ismail
You might want to look into this:
你可能想看看这个:
$("input").click(function (event) {
try {
var urlid = $(this).attr('id')
var isclass = $(this).attr('class')
if (isclass == "classname") {
alert(urlid);
event.preventDefault();
}
}
catch (err) {
alert(err);
}
});
回答by m0g3
use this :
用这个 :
var id = $(this).attr('id');
回答by vcsjones
You could use
你可以用
var id = $(this).attr('id');
回答by krs1
Using attr:
使用属性:
var id = $(this).attr('id');
.attr allows you to get html tag attributes by name.
.attr 允许您按名称获取 html 标签属性。