获取URL哈希位置,并在jQuery中使用它 [英] Getting URL hash location, and using it in jQuery

查看:131
本文介绍了获取URL哈希位置,并在jQuery中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在当前页面的URL中获得散列值后,可以将其应用于新函数中。例如。



URL可以是

  www.example.com/index.html#foo 


  $( 'UL#FOO:第一')显示(); 

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



任何帮助都会得到大量赞赏!



干杯

解决方案


编者按:严重的安全隐患,并且根据您使用的jQuery版本,可能会将您的用户暴露给XSS攻击。有关详细信息,请参阅关于此答案的评论中的可能攻击或有关安全协议栈交换的此解释的的讨论


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

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

请注意,此属性已包含符号。



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



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

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

建议:请注意, strong>可以根据需要更改哈希,向选择器注入任何内容,在使用哈希前应检查哈希。


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.

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.

Any help would be massively appreciated!

Cheers

解决方案

Editor's note: the approach below has serious security implications and, 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.

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

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 :first pseudo-selector since you are using the ID selector, is assumed that IDs are unique within the DOM.

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

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

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

这篇关于获取URL哈希位置,并在jQuery中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆