javascript - 如何通过JS在onclick事件中的HTML页面之间移动
问题描述
我有一个按钮,它有一个 onclick 事件,其中move()
调用了该函数。该函数应该移动到我编写的另一个 HTML 文件。我尝试使用window.location.href
但没有用。我在要移动的文件中有这个 HTML 正文代码(称为 fileFrom):
<body>
<button id="button1" type="button">Quit</button>
<script src="Main.js"></script>
</body>
以及 Main.js 文件中的这个 JS 代码(Main.html 是我要移动到的文件):
var button = document.getElementById("button1");
button.setAttribute("onclick", "move();");
function move() {
window.location.href = "file:///C:/Users/User/source/repos/Trivia/Main.html";
}
当我按下按钮时,页面不会改变。如何解决问题,以便在按下按钮时页面会发生变化?谢谢!
解决方案
如果您可以使用如下锚标记,我不确定您为什么要使用按钮转到其他页面:
<a href="./Trivia/Main.html">Other page</a>
否则,您可以使用eventListener,例如:
var button = document.getElementById("button1");
button.addEventListener('click', function() {
console.log('I just moved a page')
window.location.href = "#your-url-here";
});
<body>
<button id="button1" type="button">Quit</button>
<script src="Main.js"></script>
</body>
另请注意,您应该使用相对路径,./Trivia/Main.html
而不是绝对路径,如file:///C:/Users/User/source/repos/Trivia/Main.html
. 绝对路径可能不适用于服务器。关于路径的更多信息。
推荐阅读
- reactjs - 无法使用 UseAxios 构建 Gatsby,它引发错误:UnhandledPromiseRejectionWarning:错误:连接 ECONNREFUSED 127.0.0.1:80
- javascript - Webpack 无法在 Electron 应用程序中从 Nodejs 打包 https
- python - 不支持将字符串转换为浮点数 - 时间序列数据的去噪自动编码器
- c - 如何使用 CMake (Mac M1) 导入 Homebrew SDL2_image
- go - 检查 interface{} 是否指向结构
- c - 正确地将浮点数输入到结构中并打印其他提示(scanf 和 fgets 之间的区别)?
- filesystems - 仅当没有相同的文件/目录时才提取 tar
- python - nltk标签的问题
- amazon-web-services - 服务无法承担角色错误 - 使用 JDBC 目标创建 AWS Glue cloudformation
- nasm - 为什么除法后的输出是“@”符号?