【问题标题】:How to invoke javascript function when # is present in URLURL中出现#时如何调用javascript函数
【发布时间】:2021-10-22 15:48:38
【问题描述】:

当 URL 中出现 # 时,我正在尝试调用 JavaScript 函数。我知道正常行为是导航/滚动到特定标签。但找不到如何调用 JavaScript 函数。

下面的例子很接近,但没有解决我的问题。

What is the meaning of # in URL and how can I use that?

【问题讨论】:

  • if( location.href.includes("#") ) doSomething(); ?
  • @JeremyThille 我可能会使用 location.hash

标签: javascript html anchor


【解决方案1】:

假设您不只是想继续轮询该位置以查看它是否发生变化,您也许可以利用 hashchange 事件来触发该函数。

文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event

这段代码 sn-p 将监听器添加到当前页面,然后操作哈希并触发函数,显示新的哈希值。你可以在这里调用任何函数。

window.addEventListener('hashchange', function() {
    alert(location.hash);
});

window.location += "#test";

【讨论】:

  • 谢谢克里斯。这就是我一直在寻找的。负载哈希检查仍然是第一次。但在那之后,这是我需要的东西。感谢您的支持。
  • 很高兴它成功了。如果这解决了您的问题,请接受它作为答案。 :)
【解决方案2】:
var hash = window.location.hash;
if(hash){
// do something
}

【讨论】:

    【解决方案3】:
    <script>
      if (window.location.href.includes('#')) {
        // run your code here
      }
    </script>
    

    【讨论】:

      【解决方案4】:

      使用 location.hash 函数将解决您的问题

      var hash = window.location.hash.replace(/#/g, '');
      if(hash){
      // found a hash
      console.log("heyy I found a hash")'
      }
      else{
      // did not find a hash
      console.log("Uh oh")
      /*
        try using :
        window.location = window.location + '#' + "some random variable"
        to create a new URL and every time the page loads find the hash and 
        display the wanted data.
      */
      }
      

      PS:这仅适用于您的 URL 类似于 example.com/#xyz 然后它会给你 xyz 作为控制台输出。这听起来可能 模糊,但如果你这样做,你可能会得到一个想法

      【讨论】:

        猜你喜欢
        • 2012-09-30
        • 2011-02-03
        • 1970-01-01
        • 1970-01-01
        • 2014-03-15
        • 2016-05-25
        • 1970-01-01
        • 2017-12-12
        • 2017-08-24
        相关资源
        最近更新 更多