Calling function from an event

Asked

Viewed 249 times

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");}

By pressing on the link I get this error:

Uncaught Referenceerror: delete is not defined

1 answer

2


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

Check your code and put that function statement in the overall scope. That is outside of any other function you may have, DOMcontentLoad, DOMready, onLoad, etc....

An example of this situation is

HTML

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

Javascript

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

In this example the function excluir is within the anonymous function that is passed to onload and this makes it not acceptable in the global scope.

You can fix 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 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 function onload.

window.onload = function(){
    function excluir(){alert("oi");}
    document.querySelector('a').addEventListener('click', excluir);
}
  • 2

    Thanks worked out...

Browser other questions tagged

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