140

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

网址可能是

www.example.com/index.html#foo

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

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

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

4

6 回答 6

289

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

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

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

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

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

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

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

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

于 2009-11-30T21:46:25.987 回答
36

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

var hash = document.URL.substr(document.URL.indexOf('#')+1) 
于 2012-12-04T12:52:46.483 回答
6

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

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

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

于 2016-06-13T10:49:15.883 回答
3

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

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

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

于 2018-10-03T17:39:06.363 回答
2

如果当前页面有散列,我会建议先使用更好的 cek。否则会undefined

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});
于 2018-05-15T16:37:47.087 回答
2

我正在使用它来解决@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...
    }
});
于 2020-02-18T03:36:19.873 回答