Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling user defined function with params

I am defining function func1(); I want it to take some param(s) ie

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

then i want to call it later in the doc something like this:

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

but its not working.

I've been messing with it for a while but its very strange the way jquery/javascript handles user defined functions to me at least. Can some1 provide me with simple code snippet? Thx

like image 912
GoTTimw Avatar asked Jul 28 '10 00:07

GoTTimw


2 Answers

If all you want to pass is $(this), you don't need the parameter, as it will be available inside the defined function.

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

However, you can't add parameters like this:

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

Then, for your function definition, you just have

function func1() { }

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

$('#some_id').click(function () {
    func1(aaa, bbb); });
like image 176
Paul Hoffer Avatar answered Sep 20 '22 23:09

Paul Hoffer


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

Try it out: 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 wanted was reference to the element clicked, then see @phoffer's first solution.

like image 33
user113716 Avatar answered Sep 17 '22 23:09

user113716