【问题标题】:Disable hash links in URL JavaScript [duplicate]禁用 URL JavaScript 中的哈希链接 [重复]
【发布时间】:2013-04-14 20:54:42
【问题描述】:

这可能是一个简单的问题,我确信我在这里遗漏了一些东西。

我要做的就是禁用 URL 中的哈希标记链接。例如,如果有人要输入 url:www.example.com/#anchor,它将更改为 www.example.com,并完全删除 URL 中的哈希。

我什至不介意禁用该功能并将其保留在 URL 中,无论哪种方式。

这是我目前所拥有的,但我运气不佳:

var locationHashIndex = window.location.href.lastIndexOf("#"),
    station = window.location.href.slice(locationHashIndex + 1);

    window.location.href = window.location.href.substr(0, locationHashIndex);

这会不断地重新加载页面……这不是我想要的。对这个有什么想法吗?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你可以这样做:

    if(window.location.hash){
        window.location.href = window.location.href.replace(/#.*/,'');
    }
    

    【讨论】:

    • 这仍然会在每次页面加载时发生,因为您根本没有在代码周围放置任何条件。
    • 忘记我之前说的,这对我有用。
    • 很高兴它有帮助。如果这是您正在寻找的,那么有很多帮助可用于收听哈希更改。
    • /path/file.php# window.location.hash 将返回"" == false
    【解决方案2】:

    您将需要查看 window.location.hash,它存储了您要删除的值,因此您只想在其中存在 值时运行您的代码变量。

    if(window.location.hash != ''){
        // code here
    }
    

    【讨论】:

    • 我将它包裹在我当前的代码中,这似乎在刷新时有效,但是当我输入 URL 时,它不起作用。
    【解决方案3】:

    您应该使用window.history.pushState 而不是window.location.href https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history

    【讨论】:

      【解决方案4】:

      如果您愿意使用 jQuery,请参阅 https://stackoverflow.com/a/8683139/618649 以获得一个简单的解决方案,即禁用所有带有 # 的 URL。

      在这个例子中,你可以整天点击 Go There 链接,什么都不会发生。

      <html>
          <head>
              <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
          </head>
          <body>
              <a href="./#there"><span id="here">Go There...</span></a>
              <br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.
              <br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.
              <br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.
              <br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.
              <br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.
              <br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.<br/>.
              <span id="there">There...</span></a>
      
              <script language="javascript">
              jQuery(function ($) {
                  $("a[href*=#]").click(function(e) {
                      e.preventDefault();
                  });
              });
              </script>
          </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2014-04-27
        • 2021-08-06
        • 1970-01-01
        • 2019-05-21
        • 1970-01-01
        • 1970-01-01
        • 2017-07-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多