Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从URL获取片段标识符(哈希#后的值)?_Javascript_Jquery_Url_Url Fragment - Fatal编程技术网

Javascript 如何从URL获取片段标识符(哈希#后的值)?

Javascript 如何从URL获取片段标识符(哈希#后的值)?,javascript,jquery,url,url-fragment,Javascript,Jquery,Url,Url Fragment,例如: www.site.com/index.php#您好 使用jQuery,我想将值hello放入变量中: var type = … 不需要jQuery var type = window.location.hash.substr(1); 您可以使用以下代码执行此操作: var url = "www.site.com/index.php#hello"; var hash = url.substring(url.indexOf('#')+1); alert(hash); 根据A.K的代

例如:

www.site.com/index.php#您好
使用jQuery,我想将值
hello
放入变量中:

var type = …
不需要jQuery

var type = window.location.hash.substr(1);

您可以使用以下代码执行此操作:

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


根据A.K的代码在

上进行演示,下面是一个帮助函数。JS Fiddle Here()


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

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

使用以下JavaScript从URL获取哈希(#)后的值。您不需要为此使用jQuery

var hash = location.hash.substr(1);

我从这里获得了此代码和教程-

我从运行时获得了URL,下面给出了正确答案:

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

希望这对jQuery有所帮助!(只是开玩笑:+1。)我刚刚了解到一个#可以用作“散列”,它在JavaScript中用作标识符/关键字。a你也可以使用
.slice(1)
而不是
.substr(1)
,虽然这在现实生活中没有什么区别,但它应该能提供适度的性能提升。OMG,你需要检查url哈希多少次才能做出显著的改变?一百万?”在这种情况下,“适度增长”是一种极大的夸大。:-)注意:indexOf不受IE8@SchalkKeun幸运的是,现在在18年它几乎消失了。但对于那些仍然需要处理这个传奇的人来说,应该知道这一点。老实说,IE8是如此不安全,所有的支付网关基本上都将在下周(2018年6月30日)删除任何不支持TLS 1.2的浏览器,你将根本无法从他们那里进行支付。因此,这使得所有这些旧的蹩脚浏览器对任何电子商务客户端都毫无用处。var hashValue=location.hash.replace(/^#/,“”);
if
语句可以缩短为
var hash=type[1]| |“”var hash = location.hash.substr(1);
let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);