How to call an external function inside jquery code from html?

I need to load a function to retrieve data from external JS included in the HTML file, and I do this:

<body onLoad="getTicket();">
......
</body>

or that:

<html>
<body>
    <head>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/functions.js" type="text/javascript"></script>
    <script>
        $(document).ready(function() {
            getTicket();
        });
    <script>
    </head>
<body>
</html>

or that:

<html>
<body>
    <head>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/functions.js" type="text/javascript"></script>
    <script>
        getTicket();
    <script>
    </head>
<body>
</html>

And I have it in functions.JS:

functioOne() {

}

functionTwo() {

}

$(document).ready(function() {
    ...
    .....
    function getTicket() {
        //to do
    }
});

But it does not work, but on the console it displays this:

Uncaught ReferenceError: getTicket is not defined 

Sincerely.

+5
source share
5 answers

Your function is getTicketdefined only in the context (scope) of jQuery closure (anonymous function). Define it in the global scope (elsewhere in the file, and not as a "function parameter").

If you need variables from this scope, encapsulate them in a namespace (object) or declare it as window.getTicket = function() { /* ... */}.

+9
source

You can do it:

$(document).ready(function() {
  ...
  .....
  window.getTicket = function() {
    //to do
  } 
});

, getTicket

+4

function getTicket(){} doc ready:

functio One() {

}

function Two() {

}
function getTicket() {
    //to do
}

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

.

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/functions.js" type="text/javascript"></script>

.

+4

<script type="text/javascript src="external.js"></script> head.

, .

, :

  • external.js
  • ,
  • undefined

IMHO , , $(document).ready. , $(document).ready.

0

js. :

<html>
<body>
    <head>
    <!-- include script files here.(jquery and custom script files) -->
    <script>
        $(document).ready(function() {
            getTicket();
        });
    </script>
    </head>
<body>
</html>

script .

0

All Articles