问题
I want to call a function from another HTML web page I create.
If the second Javascript function is this:
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)
回答1:
The problem is you are calling testwindow.g
before the code in otherWebPage.html
has run. 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.
function f(){
var x = prompt("enter");
testwindow = window.open("otherWebPage.html", "_self");
testwindow.addEventListener('load', function(){
testwindow.g(x);
});
}
f();
回答2:
The problem is that
window.open("otherWebPage.html", "_self");
loads "otherWebPage.html" in the current page, which is unloaded.
And an unloaded page can't call functions.
来源:https://stackoverflow.com/questions/27892595/how-to-call-a-function-from-another-html-page