Why are non-anonymous functions performed when using the click event handler?

I studied the use of custom functions for event handlers. In the example below, I am trying to trigger a warning when the user clicks a button.

But a warning window appears immediately after the page loads! What am I doing wrong? (the commented part does the same).

If I define a bclick () function like

function bclick(foo, bar){ ... } 

The result is also the same.

Js in title:

 <script type="text/javascript"> var bclick = function(foo, bar){alert( foo + " " + bar + "\n");} //$(document).ready(function(){ // $("button").click(bclick("Button","Clicked")); // }); $("button").click(bclick("Button","Clicked")); </script> 

Corresponding HTML in the body:

 <button>Click Me!</button> 
+6
function jquery events
source share
3 answers

You evaluate your function before passing it on.

 $("button").click(bclick("Button","Clicked")); 

Here bclick is called with these arguments, and the result is passed to the click method. You want to pass it as a regular variable, for example:

 $("button").click(bclick); 

The obvious problem with this, however, is that you cannot pass custom arguments.

You can also pass an anonymous function that calls your function:

 $("button").click(function() { bclick("Button", "Clicked"); }); 
+17
source share

As musicfreak said. However, if you want to be very complex and use the code you have, you just need to add return this at the end of your bclick function.

+1
source share

If you want to pass arguments when setting up an event handler, another alternative is to return a function.

 $("button").click(bclick("Button","Clicked")); function bclick(foo, bar) { // called once when the event handler is setup return function(e) { // called every time the event is triggered // you still have the original `foo` and `bar` in scope, // and a new `e` (event object) every time the button is clicked console.log(foo, bar, e); }; } 
+1
source share

All Articles