首页 > 解决方案 > 链接到 HTML 中的页面并立即调用特定的 Javascript 函数

问题描述

我有两个这样的 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>

单击 file1 中的一个链接时,我想立即调用一个仅显示第 1 节或第 2 节的 Javascript 函数,具体取决于哪个链接已关闭。我怎样才能做到这一点?上面代码的问题是它调用了一个未在 file1.html 中定义的函数

标签: javascripthtml

解决方案


您不能在其他框架中调用函数,除了特定的 API,如window.postMessage(). 但这不是你想要的,我想。如果您想在页面加载时执行一个函数,您可以简单地在<script>标签中执行它,或者监听DOMContentLoaded事件,该事件将在文档构建时触发。


推荐阅读