JS/JQ获取地址栏中的链接参数

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

var url = window.location.href;

var idnex = url.substring(url.lastIndexOf("/")+1);

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

解决方案:

var lastBit = url.substring(url.lastIndexOf("/") + 1).match(/[^\/]*$/)[0];

var lastDigits = url.substring(url.lastIndexOf("/") + 1).match(/[0-9]*$/)[0];//获取的是数字部分

获取查询值

①JavaScript版:

function getUrlParam(name) {

    var age = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");

    var r = window.location.search.sunstr(1).match(reg);

    if(r != nuill) {

        return unescape(r[2]);

    }

        return null;

}

//获取http://caibaojian.com/?p=177.html;

getUrlParam('p');//输出177

 

②jQuery版

(function($){

    $.getUrlParam = function(name) {

        var age = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");

        var r = window.location.search.sunstr(1).match(reg);

       if(r != nuill) {

           return unescape(r[2]);

        }

            return null;

        }

})(jQuery);

$(function() {

    alert(window.location.href);

    alert($.getUrlParam("page"));

})

http://www.caibaojian.com/front?paeg=5;

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

2、内容扩展

    对于像下面这样的网址http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id-6#imhere

我们可以用javascript获得其中的各个部分

(一)window.location.href--------------整个URL字符串(在浏览器中就是完整地址栏)

本例返回值:http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id-6#imhere

(二)window.location.protocol------------URL的协议部分。本例返回:http:

(三)window.location.host----------------URL的主机部分 本例返回www.caibaojian.com

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

(五)window.location.pathname------------URL的路径部分(就是文件地址) 本例返回/fisker/post/0703/window.location.html

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

(七)window.location.hash----------------锚点 本例返回值:#imhere

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值