Calling a user-defined function with parameters

I define the function func1 (); I want it to accept some parameters, i.e.

var func1(aaa, bbb){ //do something, anything! }; 

then I want to call it later in the document something like this:

 $('#some_id').click(func1($this)); 

but does not work.

I have been doing this for a while, but it is very strange how jquery / javascript handles user-defined functions at least. Can some1 provide me with a simple code snippet? thanks

+6
function jquery
source share
6 answers

If all you want to pass is $(this) , you do not need a parameter, since it will be available inside a specific function.

 $('#some_id').click(func1); 

However, you cannot add such parameters:

 $('#some_id').click(func1(param1, param2)); 

Then, to define a function, you simply have

 function func1() { } 

If you need options other than $ (this), you will need to do the following:

 $('#some_id').click(function () { func1(aaa, bbb); }); 
+6
source share

I assume that you are trying to make sure that this still refers to the element that received the event.

Try: http://jsfiddle.net/jKM9s/

 $('#some_id').click(function() { func1.call(this, 'somearg', 'somearg'); }); // now "this" references the element when func1 is called function func1(aaa, bbb){ //do something, anything! }; 

EDIT:

If all you need is a link to the element clicked, then the first @phoffer solution.

+5
source share

It should be

 function func1(aaa, bbb) { ... } 
+1
source share

Here is an example:

Make sure you define your function with function . Then, when you want to call it from jQuery, you should use the built-in function in click() .

 <div>Click Me!</div> <div>Pick this one!</div> <script type="text/javascript"> function func1(aaa, bbb) { alert('You clicked the DIV that said: "' + aaa.innerHTML + '" and ' + bbb); }; $('div').click(function () { func1(this, "that ok."); }); </script> 
+1
source share

You cannot do this as $('#some_id').click(func1($this)); due to the definition of .click(handler(eventObject)) ... if you call it like this, $this in func1($this) will be expected as eventObject .

you can use .bind() and event.data .

demonstration

eg..

 function sum(event) { alert(event.data.x + event.data.y); // `this` here would refer to the element calling this function // for example, $(this).attr('id') would return `someID` if called below } 

call him

 $('#someID').bind('click',{x:4, y:5}, sum); 
0
source share

In Javascript, you cannot assign a function and pass arguments at the same time. Use anonymous function ...

 $('#some_id').click(function() { var arg1 = $(this); var arg2 = 'whatever'; return func1(arg1, arg2); }); 

If you need only one this parameter, assign a link to the function ...

 $('#some_id').click(func1); 
0
source share

All Articles