如何在jQuery中提取当前URL和ID?

3

如何使用jquery获取当前URL,或者更具体地说,获取末尾的ID呢?

例如,我有一个product.php#tab-2。我想要从中获取的只是'#tab-2'部分。

我尝试过'window.location.pathname',但这只会返回'/product.php'。

谢谢。

4个回答

8

你不需要使用jQuery来实现这个功能:

alert(window.location.href); // will give you the full url
alert(window.location.hash); // will give you the hash (#) value

请查看 Mozilla 文档,网址为 window.location - MDC


1

你需要使用 window.location.hash


0

0

要将值分配给变量,请使用以下方法;

var url = window.location.href;

var id = url.substring(url.lastIndexOf('#') + 1);

请注意,如果您的URL是以这种格式 /product.php/3 ,那么您可以使用上面的代码,只需更改lastIndexOf函数中的字符即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接