首页

通过定义JS窗口对象获取url地址location.search部分的参数值

标签:javascript,对象,示例,地址,入参,get,getParameter     发布时间:2016-08-24   

定义一个window对象 $xwoodjs并定义其子对象commonLib ,在页面中实例化路由调用params参数方法,代码详情如下: 

<!doctype html>@b@<html>@b@<head>@b@    <meta charset="UTF-8" /> @b@    <script src="http://www.xwood.net/js/jquery-1.6.2.min.js" type="text/javascript" charset="utf-8"></script> @b@    <script>@b@        window.$xwoodjs = window.$xwoodjs || {}; @b@        $xwoodjs.commonLib = (function () {@b@            return{@b@                params : function(exist,nothing){@b@                    if(location.search){@b@                        exist();                    @b@                    }else{@b@                        nothing();@b@                    }@b@                },@b@                getURLParameter : function(name){@b@                    var ret = (new RegExp("[\\?&]" + name + "=([^&#]*)")).exec(location.search);@b@                    return ret ? ret[1] : "";@b@                }              @b@            }@b@        })(); @b@    </script>@b@</head>@b@<body>@b@    <script>@b@        $(function(){@b@            //说明1. 页面加载完成后执行的函数@b@            $xwoodjs.commonLib.params(@b@                function(){@b@                    exist_fun();@b@                },@b@                function(){@b@                    nothing_fun();@b@                }@b@            ); @b@            @b@            function exist_fun(){@b@                document.writeln("params is:"); @b@                document.writeln("module =" + $xwoodjs.commonLib.getURLParameter("module")); @b@            } @b@            @b@            @b@            function nothing_fun(){@b@                document.writeln("params does not exist"); @b@            }@b@@b@        })@b@    </script>    @b@</body>@b@</html>

备注(location.href 与 location.search区别),如当前地址是http://www.xwood.net/zsk_search/?q=java

location.href获取的值(返回完整的 URL):http://www.xwood.net/zsk_search/?q=java

location.search获取到的值(从当前URL的?号开始的字符串,含“?”):?q=java