首页 > 文章列表 > 在JavaScript中,onhashchange事件的用途是什么?

在JavaScript中,onhashchange事件的用途是什么?

207 2023-09-18

当锚点部分改变时,onhashchange事件会触发。您可以尝试运行以下代码来学习如何在JavaScript中实现onhashchange事件。

示例

<!DOCTYPE html>
<html>
   <body onhashchange="newFunc">
      <button onclick="functionChange()">Click to change anchor</button>
      <script>
         function functionChange() {
            location.hash = "about";
            var hash = location.hash;
            document.write("The anchor part is now: " + hash);
         }
         // If the achor part is changed
         function newFunc() {
            alert("Anchor part changed!");
         }
      </script>
   </body>
</html>