Undefined function in window.onload?

Asked

Viewed 1,070 times

1

well I declared a function in a javascript file

javascript file:

window.onload = function(){
   function func(x,y){
      //faz operacoes em x e y e nao retorna nada
   }
}

however in the html file,when I want to call this function passing the parameters x and y

html file:

<script type="text/javascript">
     func(2,3);
</script>

he error in html file saying that the function is undefined,I’ve tried to do something like

<script type="text/javascript">
    window.onload = function() {
       func(2,3);
    }
</script>

just that it will not,it error even so saying that I did not declare the function,however I declared the function in a separate js file,does anyone know how to solve this problem? I appreciate anyone who can help

note:I’m using global variables, in addition to the fact that my algorithm is too big to put in html,so if you could tell me a way to pass the parameters of a javascript function in html it would help me a lot

  • I don’t understand why window.onload in js file, use this in html.

  • What is the order of scripts in HTML?

  • now the same order you are seeing

1 answer

2


This happens because the function func is defined only within the scope of window.onload. You need to declare it before calling it, according to this example:

//Coloquei um alert apenas para fins de teste
function func(x,y){
    alert(x + y)
}

//Aqui a função estará declarada quando chama-la
window.onload = function(){
    func(2,3);
}

//Assim, poderá chamá-la em outro lugar, por exemplo clique de botão
document.getElementById("botao").click = function () { func(2,3); }

If you declare it within the onload, it will be visible only there, and if you call it from anywhere else on the page, it will not exist, so gave the error of Undefined

  • vlw brother was what I needed to know

Browser other questions tagged

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