【问题标题】:How i can call a function from external javascript file in another external javascript file?我如何从另一个外部 javascript 文件中的外部 javascript 文件调用函数?
【发布时间】:2014-07-03 06:10:05
【问题描述】:

我有 2 个外部 JavaScript 文件。我想将第一个文件的function 调用到第二个文件中。 任何机构都可以帮助我吗? 如何从另一个外部 javascript 文件中的外部 javascript 文件调用函数?

【问题讨论】:

标签: javascript html function


【解决方案1】:

第一个 Js:

function fn1(){
//....
}

第二个Js:

function fn2(){
//....
fn1();
}

【讨论】:

    【解决方案2】:

    将两个 js 文件导入一个 html 页面,然后从任何你想要的地方调用任何你想要调用的函数

    html

    <html>
    //
    <script type="text/javascript" src="1st.js"></script>
    <script type="text/javascript" src="2nd.js"></script>
    //
    </html>
    

    1st.js

    function js1(){
    //...
    }
    

    第二个.js

    function js2(){
    js1();
    }
    

    【讨论】:

      【解决方案3】:

      JS 打印 DOM 上的值,因此一旦页面在浏览器上呈现,它就被视为一个大文档。这意味着,在解析之后,您可以从任何 JS 文件中调用任何函数

      这解释了,假设您有 2 个文件 js1.jsjs2.js,在 js1 中有 fn1(),在 js2 中有 fn2()

      因此,如果您必须在js1.js 中调用fn1(),请在js2.js 之前加载它,一旦加载,只需从js2.js 调用fn1() 即可!

      js1.js

      function fn1(){
       // some code
      }
      

      js2.js

      function fn2(){
       fn1(); //function call to another file.
      }
      

      只要保证加载顺序即可:

      <script src="js1.js" type="script/javascript"> <!-- Load the main program JS first -->
      <script src="js2.js" type="script/javascript"> <!--Load the calling program JS after it -->
      

      另一种方法

      <script src="js1.js" type="script/javascript"> //Load the main program JS first
      <script language="javascript">
         fn1(); //call the function directly from the HTML embedded JS :)
      </script>
      

      【讨论】:

        【解决方案4】:
        • 您必须确保您从中调用的脚本 函数是在你有你的脚本之后下载的 功能;
        • 当然,您调用函数的地方可以访问您调用的函数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-06
          • 2011-02-25
          • 2017-02-19
          • 2021-05-07
          • 2013-09-15
          • 2019-01-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多