Events jQuery runs automatically

Asked

Viewed 934 times

3

I have the following code:

    $(function(){
      function teste(teste){
        console.log(teste);
      }
      $('element').on('click', teste('teste'));
    })

When I execute this code the function teste is fired without me clicking the button ie automatically.

And in the following code, everything works ok.

    $(function(){
      function teste(){
        console.log('teste');
      }
      $('element').on('click', teste);
    })

Why the first code doesn’t work?

  • What is your goal here? What are you trying to do?

1 answer

7

When declaring a function, a reference to it with its name is created.

See the following example, slightly modified to "distrust" the names:

function teste(param){
    console.log(param);
}
console.log(teste);

Note that teste is a reference to the declared function. However, the moment you use the parenthesis to the right of the reference, you are directly requesting the execution of the function:

teste('teste') //executa a função 

If your intention is to pass a reference and parameters at the same time, this is not possible. At least not in this way.

A possibility to pass arbitrary parameters to a function used in on() jQuery can be found in the parameter data, in accordance with documentation.

See the following example:

$(function(){
    function teste(param) {
        console.log(param.data.teste);
    }
    $('elemento').on('click', {teste: 'teste'}, teste);
});

Passing an object with the property teste in the second argument of the function on jQuery, we can access its value when function teste is executed using the attribute data of the parameter received.

Demo at Jsfiddle

Browser other questions tagged

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