jQuery find ID of clicked button by class

2019-02-01 16:58发布

I have numerous buttons on my page with the same class names. However these buttons have different ID's. How do i do this:

$(".vote").click(function(){
     var id = $(this).{ID OF CLICKED BUTTON};
});

How can i make this pseudo code work?

Thanks

标签: jquery button
8条回答
戒情不戒烟
2楼-- · 2019-02-01 17:37

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.

查看更多
干净又极端
3楼-- · 2019-02-01 17:38

With jQuery object (not necessary)

$(".vote").click(function(){
  var id = $(this).attr('id');
});


Without jQuery object (faster)

$(".vote").click(function(){
  var id = this.id;
});
查看更多
贼婆χ
4楼-- · 2019-02-01 17:40

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);
               }
           });
查看更多
Juvenile、少年°
5楼-- · 2019-02-01 17:42
$(".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.

查看更多
霸刀☆藐视天下
6楼-- · 2019-02-01 17:44

Using attr:

var id = $(this).attr('id');

.attr allows you to get html tag attributes by name.

查看更多
贪生不怕死
7楼-- · 2019-02-01 17:57

You could use

var id = $(this).attr('id');
查看更多
登录 后发表回答