Javascript 如何使用 jQuery 从 URL 获取锚点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3552944/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:09:30  来源:igfitidea点击:

How to get the anchor from the URL using jQuery?

javascriptjqueryurlanchor

提问by zjm1126

I have a URL that is like:

我有一个像这样的网址:

www.example.com/task1/1.3.html#a_1

How can I get the a_1anchor value using jQuery and store it as a variable?

如何a_1使用 jQuery获取锚值并将其存储为变量?

回答by Silvio Delgado

For current window, you can use this:

对于当前窗口,您可以使用:

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

To get the hash value of the main window, use this:

要获取主窗口的哈希值,请使用以下命令:

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

If you have a string with an URL/hash, the easiest method is:

如果您有一个带有 URL/hash 的字符串,最简单的方法是:

var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();

If you're using jQuery, use this:

如果您使用 jQuery,请使用以下命令:

var hash = $(location).attr('hash');

回答by Nick Craver

You can use the .indexOf()and .substring(), like this:

您可以使用.indexOf()and .substring(),如下所示:

var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

You can give it a try here, if it may not have a #in it, do an if(url.indexOf("#") != -1)check like this:

您可以在这里尝试一下,如果它可能没有#,请进行如下if(url.indexOf("#") != -1)检查:

var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";


If this is the currentpage URL, you can just use window.location.hashto get it, and replace the #if you wish.

如果这是当前页面的 URL,您可以使用window.location.hash它来获取它,并根据需要替换它#

回答by Real

Use

window.location.hash

to retrieve everything beyond and including the #

检索超出并包括 # 的所有内容

回答by Valentin E

jQuery style:

jQuery 风格:

$(location).attr('hash');

回答by David Murdoch

You can use the following "trick" to parse anyvalid URL. It takes advantage of the anchor element's special href-related property, hash.

您可以使用以下“技巧”来解析任何有效的 URL。它利用了锚元素的特殊 href 相关属性hash

With jQuery

使用 jQuery

function getHashFromUrl(url){
    return $("<a />").attr("href", url)[0].hash.replace(/^#/, "");
}
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1

With plain JS

用普通的 JS

function getHashFromUrl(url){
    var a = document.createElement("a");
    a.href = url;
    return a.hash.replace(/^#/, "");
};
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1

回答by DrewB

If you just have a plain url string (and therefore don't have a hash attribute) you can also use a regular expression:

如果您只有一个普通的 url 字符串(因此没有哈希属性),您还可以使用正则表达式:

var url = "www.example.com/task1/1.3.html#a_1"  
var anchor = url.match(/#(.*)/)[1]