如何从html调用jQuery代码内的外部函数? [英] How to call external function inside jquery code from html?

查看:39
本文介绍了如何从html调用jQuery代码内的外部函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要加载功能以从HTML文件中包含的外部JS获取数据,而我正在这样做:

I need to load function to get data from external JS included in HTML file, and I'm doing this:

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

或者这个:

<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>

或者这个:

<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>

我在function.JS中有这个

And I have this in functions.JS:

functioOne() {

}

functionTwo() {

}

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

但是不起作用,并且在控制台中显示以下内容:

But does'nt work and in the console display this:

Uncaught ReferenceError: getTicket is not defined 

致谢.

推荐答案

您的 getTicket 函数仅在jQuery闭包(匿名函数)的上下文(范围)中定义.而是在全局范围内定义它(在文件的其他位置,而不是功能参数").

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

如果需要该范围的变量,请将其封装在名称空间(对象)中,或将其声明为 window.getTicket = function(){/* ... */} .

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

这篇关于如何从html调用jQuery代码内的外部函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆