您现在的位置是:首页 > 其他

李清波 2019-12-09 其他 1050 复制当前网址

js获取url参数值的方法


Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问。


hash:设置或返回从井号 (#) 开始的 URL(锚)。

host:设置或返回主机名和当前 URL 的端口号。

hostname:设置或返回当前 URL 的主机名。

href:设置或返回完整的 URL。

pathname:设置或返回当前 URL 的路径部分。

port:设置或返回当前 URL 的端口号。

protocol:设置或返回当前 URL 的协议。

search:设置或返回从问号 (?) 开始的 URL(查询部分)。


js获取url参数值的方式

一个参数:

var test =window.location.href;
var 参数=test.split("?参数=")[1];


多个参数:


方式一:

function GetQueryString(name) { 
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
  var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
  var context = ""; 
  if (r != null) 
     context = r[2]; 
  reg = null; 
  r = null; 
  return context == null || context == "" || context == "undefined" ? "" : context; 
}

调用方法:

var 参数1 = GetQueryString['参数1'];
var 参数2 = GetQueryString['参数2'];
var 参数3 = GetQueryString['参数3'];


方式二:

function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}

调用方法:

var Request = new Object();
Request = GetRequest();
var 参数1,参数2,参数3,参数N;
参数1 = Request['参数1'];
参数2 = Request['参数2'];
参数3 = Request['参数3'];
参数N = Request['参数N'];


文章来源:http://liqingbo.com/blog-1622.html

评论