如何在html中使用onclick属性从另一个网页调用一个网页的javascript函数
How to call the javascript function of one web page from another web page using onclick attribute in html?
我想从另一个网页调用一个网页的javascript函数。假设我有一个在A.html
中定义的函数myFunction()
,我想用onclick
属性在B.html
中使用它。我如何在B.html
中使用onclick
调用myFunction()
,以便它可以在A.html
中带来一些变化?
示例如下:
A.html
包含
<script>
function myFunction() {
document.getElementById("my_contents").style.display="block";
}
</script>
where B.html
<a href="Contents.html#entertainment" target="ccc" onclick="myFunction()">
<h4>Entertainment</h4></a>
你想做的是不可能的,因为HTML页面不使"本地"函数对其他网页可用。
解决您的问题:创建名为script.js
的文件。把你的javascript函数放在里面,不带<script>
标签。
在你的两个网页的<head>
标签,添加<script src="path/to/script.js"></script>
首先在窗口之间必须有一个链接,就像你打开了window.open()
的页面。
Window对象是JavaScript中的全局对象。如果两个窗口(页面)都有名称,则可以从一个窗口调用另一个窗口方法。要从子窗口调用父窗口函数,我们调用window.opener
函数。
你不能从任何页面随机调用任何页面javascript函数,就像你不能在facebook.com中调用google.com的javascript函数一样,除非使用window.open()
从google.com页面打开facebook页面。
-
您可以使用localStorage(同一域中的页面可以访问相同的存储)。
将消息/指令保存到存储器中,两个页面将通过定时器检查。 或者使用方法postMessage (https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage)如果页面B被页面a打开
有一些有趣的解决方案在stackoverflow:浏览器选项卡之间的Javascript通信/windows
解决方案示例:
A.html
<script>
setInterval(function(){
var isNeedCall = localStorage.getItem('isNeedCall');
if(isNeedCall == 'yes'){
myFunction();
localStorage.setItem('isNeedCall', 'no');
}
}, 500);
function myFunction() {
document.getElementById("my_contents").style.display="block";
}
</script>
B.html
<script>
function myFunction() {
localStorage.setItem('isNeedCall', 'yes');
}
</script>
<a href="Contents.html#entertainment" target="ccc" onclick="myFunction()">
<h4>Entertainment</h4></a>
您需要创建一个单独的文件,例如myscript.js,并使用script
标记将其链接到页面中。
从你想要实现的目标来看,听起来你必须将'A.html'中定义的"值"存储在某种形式的书面文件或SQL数据库中…然后将" b.t html"中的值填充为某种默认值,除非在存储的文件/SQL数据库中指定。这是可以实现的,但不只是HTML和Javascript正如Tom Nijs指出的那样。您可以使用PHP或Java来实现这个结果。
…或者忽略我所说的,只使用预定义值的列表/数组。
页B可以调用页a上的任何函数(如果需要的函数在窗口对象中)。这是不安全的,但它的工作。
页面:
<script>
var callFunction;
setInterval(function(){
callFunction = localStorage.getItem('callFunction');
if(callFunction && (window[callFunction] instanceof Function)){
window[callFunction]();
localStorage.setItem('callFunction', '');
}
}, 500);
function myFunction() {
document.getElementById("my_contents").style.display="block";
}
</script>
页B:
<script>
function callFunction(functionName){
localStorage.setItem('callFunction', functionName);
}
</script>
<a href="/" onclick="callFunction('myFunction')">
- 如何在javascript中点击按钮重新加载网页,但在重新加载后调用函数
- 正在创建网页,并希望将外部链接调用为html和css
- 打开网页并自动调用OnClick功能
- 如何从电子邮件内容中调用具有隐藏参数的其他网页
- 可从网页调用的Bash脚本
- 如何从AdobeAIR应用程序内的网页调用AS3代码
- 从网页调用背景.js函数
- 如何从快速呈现的 ejs 网页调用 node.js 函数
- 从网页调用服务器端C++
- 从另一个网页调用数组
- 从网页调用计算机上安装的应用程序
- 如何从网页调用Firefox扩展中定义的JS函数
- 在新的多进程Firefox中从网页调用插件
- 使用Javascript从HTML网页调用Javascript
- 从网页调用phantomjs
- 从网页调用firefox扩展main.js中的函数
- 如何在html中使用onclick属性从另一个网页调用一个网页的javascript函数
- 如何从不同服务器上的用户界面(网页)调用一台服务器上的API
- 如何从我的aspx网页调用客户端机器上的获胜应用程序
- 在javascript中从网页调用MVC方法