繁体   English   中英

从外部js文件调用位于主html中的javascript函数

[英]call javascript function located in main html from external js file

抱歉,此问题可能已经解决,但我无法找到答案。

我基本上有2个文件:

form.html代码:

<!DOCTYPE html>
<html>
<head>
<script src=".../fileA.js"></script>
<title>BACKUP MONITOR</title>
<script>
    function getEvents()
    {
        alert("getEvents");
    }

    alert("in HTML");
</script>
</head>
<body>
</body>
</html>

fileA.js代码:

alert("in fileA");
getEvents();

问题1:

我无法从fileA.js调用getEvents()。 有什么办法吗?

问题2:

我可以从form.html创建一个新的Window并从那里调用getEvents()吗? 请参见下面的代码:

新的form.html代码:

<!DOCTYPE html>
<html>
<head>
    <title>BACKUP MONITOR</title>
    <script>
        function getEvents()
        {
            alert("getEvents");
        }

        alert("in HTML");

        var w = window.open();

        var s = w.document.createElement("script");
        s.type = 'text/javascript';
        s.src = ".../fileA.js";
        w.document.body.appendChild(s);

        w.alert("New Window");
    </script>
</head>
<body>
</body>
</html>

非常感谢你

更改脚本加载的顺序。 在嵌入式脚本中定义getEvents函数之前,正在加载外部脚本.../fileA.js 如果该函数尚不存在,则无法成功调用外部脚本中的getEvents

form.html代码:

<!DOCTYPE html>
<html>
<head>
<title>BACKUP MONITOR</title>
<script>
    function getEvents()
    {
        alert("getEvents");
    }

    alert("in HTML");
</script>
<script src=".../fileA.js"></script>
</head>
<body>
</body>
</html>

您的代码应如下所示

<!DOCTYPE html>
<html>
<head>
<title>BACKUP MONITOR</title>
<script>
function getEvents()
{
    alert("getEvents");
}

alert("1");
var eventArray = getEventArray();

var w = window.open();
alert("2");
</script>
<script src=".../fileA.js"></script>
</head>
<body>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM