简体   繁体   English

链接到 HTML 页面并立即调用特定的 Javascript 函数

[英]Link to a page in HTML and immediately call a specific Javascript function

I have two HTML files like this:我有两个这样的 HTML 文件:

file1.html:
<a href="file2.html" onclick="showSection(1)">section 1 of file2</a>
<a href="file2.html" onclick="showSection(2)">section 2 of file2</a>

file2.html:
<script>
  function showSection(sectionId) {
    section = document.getElementById(sectionId);
    section.style.display = "block";
  }  
</script>
<style>
  section { display: none; }
</style>
...
<section id="1">
  Section 1
</section>
<section id="2">
  Section 2
</section>

On clicking one of link in file1, I would like to immediately call a Javascript function that only shows section 1 or 2, depending on which link was closed.在单击 file1 中的链接之一时,我想立即调用一个仅显示第 1 节或第 2 节的 Javascript 函数,具体取决于哪个链接已关闭。 How can I do this?我怎样才能做到这一点? The issue with the above code is that it calls a function which is not defined in file1.html上面代码的问题在于它调用了一个未在 file1.html 中定义的函数

You can not call functions in other frames, except for specific APIs like window.postMessage() .您不能在其他框架中调用函数,除了window.postMessage()等特定 API。 But this ist not what you want, I think.但这不是你想要的,我想。 if you want to execute a function when the page loads you can simply execute it in a <script> tag, or listen to the DOMContentLoaded event, which will fire when the document has been constructed.如果你想在页面加载时执行一个函数,你可以简单地在<script>标签中执行它,或者监听DOMContentLoaded事件,该事件将在文档被构建时触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM