Mus*_*usa 563

不需要jQuery

var type = window.location.hash.substr(1);
Run Code Online (Sandbox Code Playgroud)

  • jQuery不够!(开个玩笑:+1.) (151认同)
  • 您也可以使用`.slice(1)`代替`.substr(1)`,它应该提供适度的性能提升,尽管它在现实生活中没有任何区别. (12认同)
  • OMG,你需要多少次检查url hash才能产生明显的差异?一百万?在这种背景下,"适度增长"是一种巨大的夸大其词.:-) (3认同)
  • 我刚刚了解到#可以用作'hash',它在JavaScript中用作标识符/关键字.真棒 (2认同)

Ahs*_*hid 35

您可以使用以下代码来完成:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);
Run Code Online (Sandbox Code Playgroud)

看看演示

  • 关注IE8的@SebastiaanOrdelman?:P (8认同)
  • 说实话,IE8是如此不安全,所有的支付网关基本上将放弃任何不支持TLS 1.2的浏览器下周(2018年6月30日),你将无法完全支付他们的款项.因此,这使得所有这些旧的糟糕浏览器对任何电子商务客户端都无用. (6认同)
  • 注意:IE8不支持indexOf (4认同)
  • @SchalkKeun幸运的是,现在在'18它几乎消失了.但对于那些仍然需要处理这个传说的人来说应该意识到这一点. (4认同)

Tal*_*lha 12

var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
  hash = type[1];
alert(hash);
Run Code Online (Sandbox Code Playgroud)

关于jsfiddle的工作演示


kma*_*o23 7

这很容易。试试下面的代码

$(document).ready(function(){
  var hashValue = location.hash.replace(/^#/, '');  
  //do something with the value here  
});
Run Code Online (Sandbox Code Playgroud)

  • var hashValue = location.hash.replace(/^#/, ''); (3认同)

小智 6

使用以下JavaScript从URL获取散列(#)后的值.你不需要使用jQuery.

var hash = location.hash.substr(1);
Run Code Online (Sandbox Code Playgroud)

我从这里获得了这个代码和教程 - 如何使用JavaScript从URL获取哈希值


Man*_*ddy 5

我有运行时的URL,下面给出了正确的答案:

let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助