我想从我创建的另一个 HTML 网页调用函数。
如果第二个 Javascript 函数是这样的:
function g(x){
alert(x);
}
所以我在第一页尝试了这个:
function f(){
var x = prompt("enter");
testwindow = window.open("otherWebPage.html", "_self");
testwindow.g(x);
}
f();
但它不起作用。我哪里出错了?
(这不是我在页面中的代码,我只是举了一个简单的例子)
最佳答案
问题是您在 otherWebPage.html
中的代码运行之前调用了 testwindow.g
。您需要等待必要的功能可用。
有几种方法可以做到这一点,但这里有一个简单的例子,说明如何通过等待 load
事件来做到这一点。
function f(){
var x = prompt("enter");
testwindow = window.open("otherWebPage.html", "_self");
testwindow.addEventListener('load', function(){
testwindow.g(x);
});
}
f();
关于javascript - 如何从另一个 HTML 页面调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27892595/