如何使用 jQuery 从 URL 获取锚点? [英] How to get the anchor from the URL using jQuery?

查看:47
本文介绍了如何使用 jQuery 从 URL 获取锚点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的网址:

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

如何使用 jQuery 获取 a_1 锚点值并将其存储为变量?

How can I get the a_1 anchor value using jQuery and store it as a variable?

推荐答案

您可以使用 .indexOf().substring(),像这样:

You can use the .indexOf() and .substring(), like this:

var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

你可以在这里试一试,如果它可能没有# 在里面,像这样做一个 if(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:

var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";

<小时>

如果这是当前页面的URL,你可以使用window.location.hash来获取它,并替换# if你愿意.


If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.

这篇关于如何使用 jQuery 从 URL 获取锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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