Anonymous jQuery function passing parameters to call it

3

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');
    $('#s').html($el);
});

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

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

then call it by passing the parameter:

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

Does anyone have any idea how to perform this feat?

    
asked by anonymous 24.12.2016 / 14:05

1 answer

7

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');
    $($x).html($el);
}

jsFiddle: link

    
24.12.2016 / 14:55