简体   繁体   English

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

[英]How to get the anchor from the URL using jQuery?

I have a URL that is like: 我有一个URL,如:

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

How can I get the a_1 anchor value using jQuery and store it as a variable? 如何使用jQuery获取a_1锚值并将其存储为变量?

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');

You can use the .indexOf() and .substring() , like this: 您可以使用.indexOf().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 current page URL, you can just use window.location.hash to get it, and replace the # if you wish. 如果这是当前页面URL,您可以使用window.location.hash来获取它,如果您愿意,可以替换#

Use 使用

window.location.hash

to retrieve everything beyond and including the # 检索超出并包括#的所有内容

jQuery风格:

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

You can use the following "trick" to parse any valid URL. 您可以使用以下“技巧”来解析任何有效的URL。 It takes advantage of the anchor element 's special href-related property, hash . 它利用了anchor元素的特殊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

If you just have a plain url string (and therefore don't have a hash attribute) you can also use a regular expression: 如果你只有一个普通的url字符串(因此没有hash属性),你也可以使用正则表达式:

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

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

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