How to invoke methods directly in HTML elements in jQuery?

3

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

For example:

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

In javascript methods work like this, but not in jQuery.

Explaining better:

In the script part, I declare it 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 that same syntax in jQuery is not working. Is there a different syntax for invoking methods in jQuery or is it simply not possible to invoke methods through HTML elements?

    
asked by anonymous 02.12.2015 / 22:30

2 answers

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 to add event headphones instead of calling functions in HTML ( as @Danylo suggested ).

Even though, if the functions are in the global scope, ie outside this .ready() , you have no problems. Basically leaves within this .ready() only the functions that "initiate" the code and therefore depend on a loaded / complete page. The rest leaves out, in global scope for HTML to have 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=
}
    
02.12.2015 / 22:47
0

Use

$('seu seletor').click(function(){
   meuMetodo();
});
    
02.12.2015 / 22:42