Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass arguments in .click() function? [duplicate]

I want to pass arguments to the click() handler function in the following case:

function edit_tab(val){
    var prev_tab = $("#current_tab").html();
    if (prev_tab == 1) {
        $('.edit-basic-info').click(a); // here I want to pass some argument "a".
    }
}

How can I pass the argument a in the above code? The way I am trying to do is not working.

like image 593
Amrinder Singh Avatar asked Aug 11 '15 10:08

Amrinder Singh


2 Answers

You can use trigger()'s extraParameters to pass additional parameters to your handler:

From the trigger() documentation:

extraParameters Type: Array or PlainObject Additional parameters to pass along to the event handler.

Example (also from the documentation):

$( "#foo" ).on( "custom", function( event, param1, param2 ) {
  alert( param1 + "\n" + param2 );
});

$( "#foo").trigger( "custom", [ "Custom", "Event" ] );
like image 161
billyonecan Avatar answered Oct 19 '22 22:10

billyonecan


Use a closure:

function doSomething(myParam) {
    return function(event) {
        // Use both myParam and event here
    };
}

And in your event handler:

$('#foo').on('click', doSomething('parameter')); // Works fine

The reason this works is that the call to doSomething('parameter') returns a function, the inner function is not executed until the click handler calls it, and it can use all of the parameters passed to it from the outside.

like image 39
Madara's Ghost Avatar answered Oct 19 '22 23:10

Madara's Ghost