Call function from an event

1

I have a link that is generated via JavaScript.

<a href="#" onclick="excluir()">Excluir</a> 

I have a function in my .js.

function excluir(){alert("oi");}

When I click on the link I get this error:

  

Uncaught ReferenceError: exclude is not defined

    
asked by anonymous 14.06.2015 / 22:08

1 answer

2

This error appears because the excluir function is not in global scope.

Check your code and place this function declaration in the global scope. That is outside of any other function that might have, DOMcontentLoad , DOMready , onLoad , etc ...

An example of this is

HTML

<a href="#" onclick="excluir()">Excluir</a> 

JavaScript

window.onload = function(){
    function excluir(){alert("oi");}
}

In this example, the excluir function is inside the anonymous function that is passed to onload and this makes it unreachable in the global scope.

You can correct this by changing the code to:

function excluir(){alert("oi");} // aqui está no escopo global
window.onload = function(){
    // o código que precisa correr depois da página ter carregado
}

Or you can add the event handler via JavaScript and not inline in HTML. Note that in the example below the global scope is not polluted with variables defined within the onload function.

window.onload = function(){
    function excluir(){alert("oi");}
    document.querySelector('a').addEventListener('click', excluir);
}
    
14.06.2015 / 22:13