How to call a function from another HTML page?

给你一囗甜甜゛ 提交于 2019-12-11 04:31:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!