How to invoke methods directly in jQuery’s HTML elements?

Asked

Viewed 729 times

3

In javascript I can invoke the methods normally, but when using jQuery, it does not work.

Ex.:

<a href="#" onclick="meuMetodo()"> Link </a>

In javascript methods work like this, but in jQuery they don’t.

Explaining better:

in the script part, I declare as follows:

<script...>

$('doc...ready...

function meuMetodo(){

    //corpo do metodo

}
</script>
</head>
<body>

<a href="#" onclick="meuMetodo()"> Link </a>

</body>

In javascript, everything works. But this same jQuery syntax isn’t working. There is a different syntax to invoke the methods in jQuery or simply cannot invoke the methods through the HTML elements?

2 answers

0

Use

$('seu seletor').click(function(){
   meuMetodo();
});
  • In this way it works, but I would like to call the method through the element, instead of calling the element through the method.

  • Danylo, if you explain the answer better, +1 :)

0


It’s a matter of scope.

When you have code inside $(document).ready(function(){ ... }); you will have problems accessing functions within that scope via HTML inline. Hence it is good practice add event headphones instead of calling functions in HTML (as @Danylo suggested).

Even so, if the functions have in the global scope, ie outside that .ready() you have no problems. Basically leave inside that .ready() only functions that "start" the code and therefore depend on a loaded/complete page. The rest leaves out, in global scope for HTML to access.

An example would be:

$(document).ready(meuMetodo);

function meuMetodo(){ // esta função está no escopo global...
    // iniciar o código!

}

function clicado(e){
    // chamada por exemplo via HTML em onclick=
}
  • It worked now. By putting the method out of the "ready" boot, it works in the flame through the element. I would like to know why this practice is not considered good. You know? The most correct way to program in jQuery is to call the elements within the ready scope?

  • @Arthurcáceres takes a look here at a good explanation: http://answall.com/a/25824/129

Browser other questions tagged

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