首页 > 解决方案 > 如何通过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";
}

当我按下按钮时,页面不会改变。如何解决问题,以便在按下按钮时页面会发生变化?谢谢!

标签: javascripthtml

解决方案


如果您可以使用如下锚标记,我不确定您为什么要使用按钮转到其他页面:

<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. 绝对路径可能不适用于服务器。关于路径的更多信息。


推荐阅读