简体   繁体   English

使用 jQuery 从 URL 读取 #hash

[英]Read #hash from URL with jQuery

如何使用 jQuery 从 URL 返回website.com/#something (something) 的哈希值?

window.location.hash its that simple. window.location.hash就是这么简单。

donot use all those methods which consume CPU and effects performance.不要使用所有消耗 CPU 和影响性能的方法。

If DOM provides something predefined use it first.如果 DOM 提供了一些预定义的东西,请先使用它。

To pass value to PHP please do and ajax call to php.要将值传递给 PHP,请执行和 ajax 调用 php。

var hash = window.location.hash;

$.ajax({
    url: 'someurl.php',
    data: {hash: hash},
    success: function(){}
})

您可以使用location.hash属性来获取当前页面的哈希值:

var hash = window.location.hash;

update更新

As there is a built in method to get the hash via DOM above answer is not appropriate由于有一个内置的方法可以通过 DOM 获取哈希,所以上面的答案是不合适的

   var hashTag = window.location.hash
   alert(hashTag);

will do the magic.会变魔术。

Old answer旧答案

You can do something as below if you have multiple hashes in your url如果您的网址中有多个哈希值,您可以执行以下操作

//var href = location.href; // get the url in real worl scenario
var href = "www.bla.com#myhashtag"; // example url
var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
var afterSplit = "Error parsing url";
if(split[1] != null){
    afterSplit = split[1];
}
// If everything went well shows split[1], if not then de default error message is shown
alert(afterSplit);

Here is an example Live Fiddle这是一个示例Live Fiddle

You can use javascript to get the hash and pass it onto jquery. 您可以使用javascript获取哈希值并将其传递给jquery。

Ex: 例如:

var url = window.location.href;
var hash = url.substring(url.indexOf('#'));                          
$(hash).trigger('click');

你可以用这个

h=new URL(location).hash.split`&`.find(e=>/hash_name/.test(e)).split`=`[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM