如何从另一个HTML页面调用一个函数? [英] How to call a function from another HTML page?

查看:705
本文介绍了如何从另一个HTML页面调用一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果第二个Javascript函数是这样的话:

  function g(x){
alert(x);
}

所以我在第一页尝试了这个:

 函数f(){
var x = prompt(enter);
testwindow = window.open(otherWebPage.html,_self);
testwindow.g(x);
}
f();

但它不起作用。

(这不是我在页面中的代码,我只是举了一个简单的例子)

解决方案

问题是您在 otherWebPage.html 中的代码前调用 testwindow.g code>已运行。您需要等待必要的功能。



有几种方法可以做到这一点,但这里有一个简单的例子,说明如何通过等待 load event。

  function f(){
var x = prompt(enter);
testwindow = window.open(otherWebPage.html,_self);
testwindow.addEventListener('load',function(){
testwindow.g(x);
});
}
f();


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)

解决方案

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();

这篇关于如何从另一个HTML页面调用一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆