如何在html中使用onclick属性从另一个网页调用一个网页的javascript函数

How to call the javascript function of one web page from another web page using onclick attribute in html?

本文关键字:网页 调用 一个 函数 javascript 另一个 html 属性 onclick      更新时间:2023-09-26

我想从另一个网页调用一个网页的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页面。

  1. 您可以使用localStorage(同一域中的页面可以访问相同的存储)。

  2. 将消息/指令保存到存储器中,两个页面将通过定时器检查。
  3. 或者使用方法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')">