The difference between `.click (handler ()) and`.click (handler)`

I have the following code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="jquery-1.4.2.min.js" ></script> <script type="text/javascript"> function myFun() { alert(5) } $(document).ready(function(){ $("#myID").click(myFun()); }) </script> </head> <body> <input type="button" value="Click it" id="myID" /> </body> </html> 

When I run this code, then alert(5) comes when the page loads. If i write

 $("#myID").click(myFun) 

This warning appears only when the button is pressed. Why is he acting like that?

+6
source share
4 answers
 $("#myID").click(myFun()); 

This calls myFun() and tries to set everything that it returns as an event handler. Since it does not return anything, you actually trigger a click on #myID .

+10
source

Read this one . click () - attach an event handler to a JavaScript click event or trigger this event for an element using JavaScript.

You just need to write $("#myID").click(myFun); instead of $("#myID").click(myFun()); , because when you write myFun() in your code, the function is called immediately (and not when the click event fires with #myID ).

Working demo

+3
source

Try this to run the function in the click event:

 function myFun(){ alert(5); } $(document).ready(function(){ $("#myID").click(function(){ myFun(); }); }) 
+2
source

Try the following:

It will work

 $(document).ready(function() { function myFun() { alert(5) } $("#myID").click(function(){ myFun(); }); });​ 
+2
source

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


All Articles