[英]How to call a function from another HTML page?
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) (这实际上不是页面中的代码,我只是举了一个简单的例子)
The problem is you are calling testwindow.g
before the code in otherWebPage.html
has run. 问题是你在呼唤
testwindow.g
在代码前otherWebPage.html
已运行。 You need to wait for the necessary function to be available. 您需要等待必要的功能可用。
There are several ways to do this, but here is a simple example for how to do this by waiting for the load
event. 有几种方法可以执行此操作,但是这里有一个简单的示例,说明如何通过等待
load
事件来执行此操作。
function f(){
var x = prompt("enter");
testwindow = window.open("otherWebPage.html", "_self");
testwindow.addEventListener('load', function(){
testwindow.g(x);
});
}
f();
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. 并且已卸载的页面无法调用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.