Find the button object that raised the event with jquery or javascript

I use jquery to bind events to multiple buttons ...

$(".numField").bind("click", stageButtonClick()); 

In the stageButtonClick() function, I want to get the object of the calling button, but I can not use $(this) inside the stageButtonClick function, it does not return anything to me.

In addition, it is not recommended to use the built-in function.

 $(".numField").bind("click", function() {...}) 

I would like to know how to do it.

+1
source share
4 answers

Your problem is here:

 $(".numField").bind("click", stageButtonClick()); don't use parenthesis ^^ 

Do not use parentheses when assigning a named function, because it will call the function and assign the result instead.

It works:

Demo

 $(document).ready(function(){ $(".numField").bind("click", stageButtonClick); }); function stageButtonClick() { alert( $(this).attr("id") ); } 
+2
source

You are trying to do something very non-jQuery. Even if you don’t need the whole built-in function, you can make your life much easier by doing something like this:

 $(".numField").bind("click", function() { stageButtonClick(this); // or stageButtonClick($(this)) if you want to pass jQuery selector }); 

Here you simply pass the clicked DOM element to your stageButtonClick() function.

Also, if you are using jQuery 1.7 or higher, you really should use on() instead of bind() .

+1
source

First $(".numField").bind("click", stageButtonClick()); will not work because stageButtonClick() returns the result of the stageButtonClick function, not the function itself

Secondly, the event object is passed to the called function using the target element and currentTarget . Normal, event.currentTarget will be .numField .

So try with $(".numField").bind("click", stageButtonClick); , and you can usually use $(this) or $(event.currentTarget)

+1
source

If so, you can use event object

 $(".numField").bind("click", stageButtonClick); function stageButtonClick(e){ // You can just use **this** OR **$(e.target)** } 

Also bind the event using .on() instead of .bind() , since the previous one was replaced by the first.

 $(".numField").on("click", stageButtonClick); 
+1
source

Source: https://habr.com/ru/post/1493482/


All Articles