javascript 如何从另一个 HTML 页面调用函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27892595/
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
How to call a function from another HTML page?
提问by Tomer Solomon
I want to call a function from another HTML web page I create.
我想从我创建的另一个 HTML 网页调用一个函数。
If the second Javascript function is this:
如果第二个 Javascript 函数是这样的:
function g(x){
alert(x);
}
So I tried this in the first page:
所以我在第一页尝试了这个:
function f(){
var x = prompt("enter");
testwindow = window.open("otherWebPage.html", "_self");
testwindow.g(x);
}
f();
but its not working. Where did I go wrong?
但它不工作。我哪里做错了?
(it's not really my code in the page, i just gave a simple example)
(这不是我在页面中的代码,我只是举了一个简单的例子)
回答by Alexander O'Mara
The problem is you are calling testwindow.gbefore the code in otherWebPage.htmlhas run. You need to wait for the necessary function to be available.
问题是您testwindow.g在代码otherWebPage.html运行之前调用。您需要等待必要的功能可用。
There are several ways to do this, but here is a simple example for how to do this by waiting for the loadevent.
有几种方法可以做到这一点,但这里有一个简单的例子,说明如何通过等待load事件来做到这一点。
function f(){
var x = prompt("enter");
testwindow = window.open("otherWebPage.html", "_self");
testwindow.addEventListener('load', function(){
testwindow.g(x);
});
}
f();
回答by Oriol
The problem is that
问题是
window.open("otherWebPage.html", "_self");
loads "otherWebPage.html" in the current page, which is unloaded.
在卸载的当前页面中加载“otherWebPage.html”。
And an unloaded page can't call functions.
并且卸载的页面不能调用函数。

