调用外部 javascript 文件的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2935045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:33:53  来源:igfitidea点击:

Calling a function of en external javascript file

asp.netjavascriptpathcall

提问by OrElse

In general... How can I make a call on a function of an external java script file?

一般情况下...如何调用外部 java 脚本文件的函数?

More specific...

更加具体...

  • In the head tag i have
  • 在 head 标签中,我有

<script type="text/javascript" src="JScript/FontSize.js"></script>

<script type="text/javascript" src="JScript/FontSize.js"></script>

  • The external javascript file, (that i would like to call) FontSize.jscontains the following functions.

    function checkCookie()
    
    function setCookie(c_name, value, expiredays)
    
    function getCookie(c_name)
    
    function increaseFontSize()
    
    function decreaseFontSize()`
    
  • The FontSize.js is located at the ~/Jscript/directory

  • 外部 javascript 文件(我想调用)FontSize.js包含以下函数。

    function checkCookie()
    
    function setCookie(c_name, value, expiredays)
    
    function getCookie(c_name)
    
    function increaseFontSize()
    
    function decreaseFontSize()`
    
  • FontSize.js 位于~/Jscript/目录

I guess the body on load should contain something like

我想负载上的身体应该包含类似的东西

<body onload="/JScript/Fontsize.js/checkCookie()">

<body onload="/JScript/Fontsize.js/checkCookie()">

Of course nothing works as it should because, i do not know how to make the call to a function to an external js file

当然,没有什么是应该的,因为,我不知道如何调用外部 js 文件的函数

回答by Nick Craver

You just call it as if it were local :)

您只需将其称为本地即可:)

<body onload="checkCookie()">

Or, do it in script:

或者,在脚本中执行:

window.onload = checkCookie;

When you declare a function and it's not in another object/namespace, it's just globally available, and you can call it as if it immediately preceded your current code. By default these functions will be on the windowobject, you can see a short demo here.

当您声明一个函数并且它不在另一个对象/命名空间中时,它只是全局可用的,您可以调用它,就好像它紧跟在您当前的代码之前一样。默认情况下,这些函数将在window对象上,您可以在这里看到一个简短的演示

For example (doesn't matter wherethis function's defined, external or not):

例如(不管这个函数在哪里定义,外部与否):

function myFunc() { alert('hi'); }
myFunc();
window.myFunc(); //same call, unless there's *another* myFunc in a local-er scope

回答by Gowtham

  <html>
        <head>
            <script type="text/javascript" language="javascript" src="main.js"></script>
        </head>
        <body>

    <!--The extranal main.js file contains samp() function.. -->
            <script>
              <!--    samp(); -->
            </script>
        </body>
    </html>