简体   繁体   中英

Calling Javascript function from external file when loading html page

I want to load a function named james() from a Javascript file named hello.js which is added as an external file to index.html .

My problem is when the function james is declared inside $(document).ready(function()) , it just says that 'james function is undefined' and is not called. How can I call function declared inside document.ready using onload?

<html>
<head>
</head>
<body onload= "james()">
         <script src=hello.js>
</body>
</html>

hello.js javascript file

function mountApp{

   $(document).ready(function(){

      function james(){
      alert("how can i get call ,when html page is loaded");
     }
 });
}

Your "james" function does not exist in the correct scope. It is declared inside the "ready" event listener and only exists inside the listener scope. After that, it won't be available anymore.

You cannot do what you are trying to do. Functions cannot be used outside of the scope they were declared in. Move the function to the global scope instead.

function mountApp{

   $(document).ready(function(){
     // You can call the function from here
     james();
   });
}

function james(){
  alert("how can i get call ,when html page is loaded");
}

Now, I don't see why you would be adding an event listener "onready" inside a function, because function calls will only be executed after the DOM is ready, so it will never trigger.

true method is, you create function outside document.ready function and then call

function james()
{
  alert("how can i get call ,when html page is loaded");
}
$(document).ready(function(){
 james();
)};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM