简体   繁体   中英

How can i invoke a function within Javascript when its already invoked with onload or document.ready?

So when my php page loads I want to execute a function and right now that function looks like this:

$(document).ready(function mytest() {
      //Some code
  });

This works fine but in that same java-script file i want to be able to invoke that "mytest()" function like a regular function but it doesn't work by just writing:

mytest();

Is there a way I can manually invoke this method?

Change code like this:

<?php
  /* php part */
?>
<!-- HTML PART -->
<script>
/* my fn */
function mytest() {

}
/* on load */
$(document).ready(function(){
  // call nr 1
  mytest();
  // call nr 2
  mytest();
  // etc...
});
</script>

"mytest" function inside $(document).ready(...) is not available outside. You can define "mytest" first in global scope and then invoke it in $(document).ready(...) and in anywhere you want.

function mytest() {
    //Some code
}

$(document).ready(function() {
    mytest();
});

...
mytest();

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