从当前网址获取#id [英] Getting the #id from current URL

查看:135
本文介绍了从当前网址获取#id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用JavaScript从当前URL检索#anchor部分的方法. 例如:

I'm looking for a way to retrieve the #anchor part from the current URL with JavaScript. For example:

http://my-page.com/index.html#contact-us

将返回contact-us.

我可以在最终的#处分割URI,然后进行最后一部分处理,但是我正在寻找一个更好,更简洁的建议.原生(jQuery?)函数会很棒,但是我想我要的太多了.

I could split the URI at the eventual # and then take the last piece, but I'm looking for a somewhat nicer and cleaner suggestion. A native (jQuery?) function would be great, but I guess I'm asking for too much.

推荐答案

使用 location.hash :

location.hash.slice(1);

#开头,因此以.slice(1)开头.给定任意字符串,您可以通过创建<a>元素来使用内置的URL解析功能,并设置href,然后 read 其他属性,例如protocolhostnamehash等jQuery示例:

It starts with a #, hence .slice(1). Given an arbitrary string, you can use the built-in URL-parsing feature by creating a <a> element, and set the href, then read other properties, such as protocol, hostname, hash, etc. jQuery example:

$('a').attr('href', url)[0].hash;

这篇关于从当前网址获取#id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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