使用 jQuery 从 URL 读取 #hash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15741421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read #hash from URL with jQuery
提问by Sandeep
How can I return the hash value of website.com/#something
(something) from the URL with jQuery?
如何website.com/#something
使用 jQuery 从 URL返回(某物)的哈希值?
回答by Sandeep
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(){}
})
回答by Eli
You can use the location.hashproperty to grab the hash of the current page:
您可以使用location.hash属性来获取当前页面的哈希值:
var hash = window.location.hash;
回答by Jay Mayu
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
回答by CodeMonkey
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');