JavaScript获取URL参数

文件1:realwall.js

(function(window){
    var urltool = {
        getUrlParameterByKey : function(url,key){
            var result = "",
                start,
                parameterStr,
                len,
                paras,
                i;
            parameterStr = url.split("?");
            if(parameterStr.length > 1){
                parameterStr = parameterStr[1];
                parameterStr = parameterStr.split("#");
                parameterStr = parameterStr[0];
                if(parameterStr != ""){
                    paras = parameterStr.split("&");
                    len = paras.length;
                    for(i = 0; i < len; i++){
                        start = paras[i].indexOf(key + "=");
                        if(start == 0){
                            result = paras[i].replace(key + "=", "");
                            break;
                        }
                    }
                }
            }
            return result;
        }
    };
    window.urltool = urltool;
})(window);

文件2:here.js

/*
 * 调用urltool对象,获取URL中指定参数,如果要传中文的参数,需对原始URL链接中的中文参数用encodeURIComponent("参数")进行编码,然后再对结果字符串用decodeURIComponent()解码 */
window.onload = function(){
    var url = window.location.href;
  var search = window.location.search;
  alert(urltool.getUrlParameterByKey(search, "id")); 
    alert(urltool.getUrlParameterByKey(url, "id"));
};

参考:http://www.cnblogs.com/zhaoshun/archive/2009/01/09/1372437.html

原文地址:https://www.cnblogs.com/realwall/p/2166032.html