javascript - 链接到 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 中定义的函数
解决方案
您不能在其他框架中调用函数,除了特定的 API,如window.postMessage()
. 但这不是你想要的,我想。如果您想在页面加载时执行一个函数,您可以简单地在<script>
标签中执行它,或者监听DOMContentLoaded
事件,该事件将在文档构建时触发。
推荐阅读
- ios - 向 Ionic 4 项目添加 cordova-plugin-firebase-dynamiclinks 导致无法构建
- three.js - 将 DeviceOrientationControls 添加到 GLTF GLB 对象
- java - 为什么 System.getProperty("java.io.tmpdir") 在 Mac OS X Catalina 10.15 上返回只读目录
- python - 使用 BeautifulSoup 抓取 OSHA 网站
- python - 双曲曲线_拟合的预测区间 - SciPy
- php - 处理 PHP 多维数组以将键分配为值数组的父级
- r - stringr: how to recover sentences from a string that was derived from concatenating those sentences
- ios - How to convert a line of code from Objective-C to Swift in sorting array?
- php - 向 Stripe Checkout 会话添加免费的 0 美元商品
- system-verilog - 有没有办法将 SystemVerilog 分配模式转换为打包结构?