宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

本文将通过实际例子讲解怎么使用javascript或者jquery获取地址url参数,希望你会喜欢。

问题描述

今天做一个主题,有一个需求是根据不同的页面来做,虽然php也可以做到,不过考虑到自己的特效代码都是在jQuery上完成,想着能否直接通过获取地址栏中的链接参数里面的数字直接来实现效果。

假设页面的地址是这样子的。http://caibaojian.com/p/165 ,那么我要获取最后的一个数字165,可以通过这样子的代码

var url= window.location.href;
var index = url.substringurl.lastIndexOf'/') + 1);

但是这样子有缺陷,假如我获取到的地址不是这样子的形式,而是http://caibaojian.com/tools的话,那么这个index的值就不是一个数字了。

解决方案

下面这种可能会更好呢?

var lastBit = url.substringurl.lastIndexOf'/') + 1).match/[^/]*$/)[0];
var lastDigits = url.substringurl.lastIndexOf'/') + 1).match/[0-9]*$/)[0];  // 获取的是数字部分

获取查询值

JavaScript版:

function getUrlParamname){
    var reg = new RegExp"^|&)"+ name +"=[^&]*)&|$)");
    var r = window.location.search.substr1).matchreg);
    if r!=null) return unescaper[2]); return null;
}
//获取http://caibaojian.com/?p=177.html的p值
getUrlParam'p'); //输出177

jQuery版:

<script type="text/javascript">
function$){
$.getUrlParam = functionname)
{
var reg = new RegExp"^|&)"+ name +"=[^&]*)&|$)");
var r = window.location.search.substr1).matchreg);
if r!=null) return unescaper[2]); return null;
}
})jQuery);
$function){
alertwindow.location.href);
alert$.getUrlParam'page'));
})
</script>

http://www.caibaojian.com/front?page=5

当一个页面的地址是上面这个,那么我们使用了上面的jQuery代码,就会弹出一个数字5了。

内容扩展

对于像下面这样的网址
http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere
我们可以用javascript获得其中的各个部分
1, window.location.href———–整个URl字符串在浏览器中就是完整的地址栏)
本例返回值: http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

2,window.location.protocol———URL 的协议部分
本例返回值:http:

3,window.location.host———-URL 的主机部分
本例返回值:www.caibaojian.com

4,window.location.port—–URL 的端口部分
如果采用默认的80端口update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:””

5,window.location.pathnameURL 的路径部分就是文件地址))
本例返回值:/fisker/post/0703/window.location.html

6,window.location.search——-查询参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?ver=1.0&id=6

7,window.location.hash——-锚点
本例返回值:#imhere