location对象是window对象下的一个属性,用的时候可以省略window对象
location可以获取或者设置浏览器地址栏的URL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
<script>
//对象中的属性和方法
//location对象
console.log(window.location);
//地址栏上#及后面的内容
console.log(window.location.hash);
//主机名及端口号
console.log(window.location.host);
//主机名
console.log(window.location.hostname);
//文件的路径---相对路径
console.log(window.location.pathname);
//端口号
console.log(window.location.port);
//协议
console.log(window.location.protocol);
//搜索的内容
console.log(window.location.search);
onload=function () {
document.getElementById("btn").onclick=function () {
// 设置跳转的页面的地址
location.href="http://www.jd.com";//属性----------------->必须记住
location.assign("http://www.jd.com");//方法
location.reload();//重新加载--刷新
location.replace("http://www.jd.com");//没有历史记录
};
};
</script>
</head>
<body>
<input type="button" value="显示效果" id="btn"/>
</body>
</html>
统一资源定位符 (Uniform Resource Locator, URL)
scheme://host:port/path?query#fragment
scheme:通信协议
常用的http,ftp,maito等
host:主机
服务器(计算机)域名系统 (DNS) 主机名或 IP 地址。
port:端口号
整数,可选,省略时使用方案的默认端口,如http的默认端口为80。
path:路径
由零或多个'/'符号隔开的字符串,一般用来表示主机上的一个目录或文件地址。
query:查询
可选,用于给动态网页传递参数,可有多个参数,用'&'符号隔开,每个参数的名和值用'='符号隔开。例如:name=zs
fragment:信息片断
字符串,锚点.
使用chrome的控制台查看
查MDN
MDN
成员
解析URL中的query,并返回对象的形式
function getQuery(queryStr) {
var query = {};
if (queryStr.indexOf('?') > -1) {
var index = queryStr.indexOf('?');
queryStr = queryStr.substr(index + 1);
var array = queryStr.split('&');
for (var i = 0; i < array.length; i++) {
var tmpArr = array[i].split('=');
if (tmpArr.length === 2) {
query[tmpArr[0]] = tmpArr[1];
}
}
}
return query;
}
console.log(getQuery(location.search));
console.log(getQuery(location.href));
联系客服