从一个需要另一个的JavaScript文件调用函数

时间:2013-07-05 04:33:11

标签: javascript html

我正在尝试从另一个JavaScript文件调用一个JavaScript文件中编写的函数。我有以下代码,但它不起作用:

我的HTML文件

<script type="text/javascript" src="js1.js"></script>
<script type="text/javascript" src="js2.js"></script>
<script language="javascript">
    js1();
</script>

js1.js

function js1()
{
    alert("Hello from js1");
    js2();
}

js2.js

function js2() 
{
    alert("Hello from js2");
}

我该怎么办?

2 个答案:

答案 0 :(得分:6)

尝试更改订单

<script type="text/javascript" src="js2.js"></script>
<script type="text/javascript" src="js1.js"></script>
<script language="javascript">
   js1();
</script>

因为您在js2();内拨打了js1.js,所以应该先执行脚本js2.js

在您的情况下,我认为它仍然可以在不更改此类订单的情况下工作,因为您在函数内部调用了js2();。执行此脚本时:

function js1()
{
   alert("Hello from js1");
   js2();
}

即使js2.js尚未执行,但您 此时实际调用js2();

试试它是否有效。

答案 1 :(得分:2)

我将假设这是您的整个 HTML页面。

为了让这些脚本运行,您需要将这些JavaScript文件放在与您的网页相同的文件夹中,并实际拥有一个合适的HTML页面!

在HTML页面中,您需要在头部或正文中包含对js1和js2文件的引用,并将您在HTML页面本身中编写的脚本包含在正文中,以便它在执行时执行它载满了:

<!DOCTYPE html>
<!-- ^ Declaring this DOCTYPE means this is a HTML5 page. -->
<html>
    <head>
        <!-- This will load your scripts into the document. -->
        <script src="js1.js"></script>
        <script src="js2.js"></script>
        <!--
            In a HTML5 page, you don't need to include the
            'type="text/javascript"' attribute on script tags.
            They're treated as having that by default, unless you say otherwise.
        -->
    </head>
    <body>
        <!--
            You could also include your scripts here, but I'll
            just leave these commented out since they're already included.
        <script src="js1.js"></script>
        <script src="js2.js"></script>
        -->
        <script>
        js1();
        </script>
        <!--
            You don't need 'language="javascript"' on a script tag.
            Use the type attribute, or nothing in a HTML5 page.
        -->
    </body>
</html>