Anonymous jQuery function passing parameters when calling it

Asked

Viewed 327 times

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 determining them when calling the function, just as it is done in the traditional way.

Example: I have the function with certain elements:

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

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

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

and then call it by passing the parameter:

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

Does anyone have any idea how to perform this feat?

  • Your logic is right, you had some mistake or difficulty implementing?

  • Sergio, calling a jquery script in traditional js way does not work. See: https://jsfiddle.net/g83v0vnr/20/

  • Ah, I got it. You have to do it like this: https://jsfiddle.net/g83v0vnr/21/

  • 1

    Perfect!! Sergio put the solution as an answer for me to vote. Valeuuuu!

1 answer

7


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

When you use a named function, passing inline in HTML then 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 function argument. And then inside the function you can do so:

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

jsFiddle: https://jsfiddle.net/g83v0vnr/21/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.