【问题标题】:How to move between HTML pages in onclick event through JS如何通过JS在onclick事件中的HTML页面之间移动
【发布时间】:2021-05-07 15:04:27
【问题描述】:

我有一个按钮,它有一个 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";
}

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

【问题讨论】:

  • 你不应该使用这样的绝对路径。您应该使用相对路径 ./Trivia/Main.html
  • 如果任何答案帮助/回答了您的问题,您应该将其标记为此类。这将对其他人有所帮助。

标签: javascript html


【解决方案1】:

如果您可以使用 anchor tag 之类的,我不确定您为什么要使用按钮转到其他页面:

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

【讨论】:

    【解决方案2】:

    在按钮标签内为您的另一个 html 文件添加一个锚点。

    【讨论】:

    • 什么是锚?我怎样才能把它交给按钮?
    • 正如您从 OP 的评论中注意到的那样,这不是很清楚。这也不是真正的答案或评论。但是,如果这应该是一个答案,您至少应该添加一些代码。
    【解决方案3】:

    只需参考带有锚标记的页面即可。

    <a href="./Trivia/Main.html">Quit</a>
    

    【讨论】:

      【解决方案4】:
      <body>
          <button id="button1" type="button">Quit</button>
      </body>
      <script>
      var button = document.getElementById("button1");
      button.setAttribute("onclick", "move();");
      function move() {
      alert("hi");
      window.location.href = "file:///C:/Users/User/source/repos/Trivia/Main.html";
      }
      </script>
      

      如果它不能正常工作,file:///C:/Users/User/source/repos/Trivia/Main.html 请检查具体路径。

      【讨论】:

        猜你喜欢
        • 2021-03-17
        • 2014-09-29
        • 1970-01-01
        • 2020-02-07
        • 1970-01-01
        • 1970-01-01
        • 2020-08-18
        • 1970-01-01
        • 2020-05-21
        相关资源
        最近更新 更多