获取 URL 哈希位置,并在 jQuery 中使用它

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

Getting URL hash location, and using it in jQuery

jqueryurlhashfragment-identifier

提问by Robbie White

I'd like to get the value after a hash in the URL of the current page and then be able to apply this in a new function... eg.

我想在当前页面的 URL 中的散列之后获取值,然后能够将其应用于新函数中......例如。

The URL could be

网址可能是

www.example.com/index.html#foo

And I would like to use this in conjunction with the following piece of code

我想将它与以下代码结合使用

$('ul#foo:first').show();

I'm kinda assuming/hoping there is some way of grabbing this, and turning it into a variable that I can then use in the second piece of code.

我有点假设/希望有某种方法可以抓住它,并将其变成一个变量,然后我可以在第二段代码中使用它。

回答by CMS

Editor's note:the approach below has serious security implicationsand, depending upon the version of jQuery you are using, may expose your users to XSS attacks. For more detail, see the discussion of the possible attack in the comments on this answer or this explanation on Security Stack Exchange.

编者注:以下方法具有严重的安全隐患,并且根据您使用的 jQuery 版本,可能会使您的用户受到 XSS 攻击。有关更多详细信息,请参阅此答案的评论或Security Stack Exchange 上的此解释中对可能的攻击的讨论。

You can use the location.hashproperty to grab the hash of the current page:

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

var hash = window.location.hash;
$('ul'+hash+':first').show();

Note that this property already contains the #symbol at the beginning.

请注意,此属性已包含#开头的符号。

Actually you don't need the :firstpseudo-selector since you are using the ID selector, is assumed that IDs are uniquewithin the DOM.

实际上您不需要:first伪选择器,因为您使用的是ID 选择器,假设 ID在 DOM 中是唯一的。

In case you want to get the hash from an URL string, you can use the String.substringmethod:

如果您想从 URL 字符串中获取哈希值,可以使用以下String.substring方法:

var url = "http://example.com/file.htm#foo";
var hash = url.substring(url.indexOf('#')); // '#foo'

Advice:Be aware that the user can changethe hash as he wants, injecting anything to your selector, you should check the hash before using it.

建议:请注意,用户可以根据需要更改散列,向您的选择器注入任何内容,您应该在使用前检查散列。

回答by Deepak Patil

location.hash is not safe for IE, in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL

location.hash 对于 IE 是不安全的,在 IE(包括 IE9)的情况下,如果您的页面包含 iframe,则在 iframe 内容中手动刷新后获取 location.hash 值是旧的(第一页加载的值)。而手动检索的值与 location.hash 不同,所以总是通过 document.URL 检索它

var hash = document.URL.substr(document.URL.indexOf('#')+1) 

回答by Matas Vaitkevicius

For those who are looking for pure javascript solution

对于那些正在寻找纯 javascript 解决方案的人

 document.getElementById(location.hash.substring(1)).style.display = 'block'

Hope this saves you some time.

希望这可以为您节省一些时间。

回答by j08691

Since jQuery 1.9, the :targetselector will match the URL hash. So you could do:

从 jQuery 1.9 开始,:target选择器将匹配 URL 哈希。所以你可以这样做:

$(":target").show(); // or $("ul:target").show();

Which would select the element with the ID matching the hash and show it.

这将选择 ID 与哈希匹配的元素并显示它。

回答by Chetabahana

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

如果当前页面有哈希值,我会建议先使用更好的 cek。否则就会undefined

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});

回答by squarecandy

I'm using this to address the security implications noted in @CMS's answer.

我正在使用它来解决@CMS 回答中提到的安全隐患。

// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});