Anonymous jQuery function passing parameters to call it

Posted on

Question :

Is it possible to pass parameters in a jQuery function so that I can use it multiple times with multiple elements? I need to leave it with indeterminate elements and pass them as parameters by determining them when calling the function, just as it is done in the traditional way.

Example: I have the function with determined elements:

$('button').click(function() {
    $el = $(this).closest('[id]').attr('id');

I need it more or less like this, with undetermined elements:

function teste($x){
        $el = $(this).closest('[id]').attr('id');

then call it by passing the parameter:

<button onclick="teste('meuID');">Pronto</button>

Does anyone have any idea how to perform this feat?


Answer :

The problem is that $('button').click(function() { passes the clicked element as the execution context of this anonymous function. That is, this is button clicked.

When you use a named function, passing inline in HTML there the execution context is another, ie window . But you can use onclick="teste('#meuID', this);" and there will be passed a reference of the element clicked as argument of the function. And then inside the function you can do this:

function teste($x, self) {
    $el = $(self).closest('[id]').attr('id');

jsFiddle: link


Leave a Reply

Your email address will not be published. Required fields are marked *