1. location对象:window.location对象用于获取当前页面的地址(URL),并把浏览器重定向到新的页面。
2. location对象的属性:location.hostname返回web主机的域名
location.pathname返回当前页面的路径和文件名
location.port返回web主机的端口
location.protocol返回所使用的web协议(http://或https://)
location.href属性返回当前页面的URL
location.assign()方法加载新的文档。
demo代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<p></p>
<script type="text/javascript">
var btn1 = document.getElementsByTagName("button")[0];
var btn2 = document.getElementsByTagName("button")[1];
var p = document.getElementsByTagName("p")[0];
btn1.onclick = function(){
console.log(window.location.hostname);//web主机域名
console.log(window.location.pathname);
console.log(window.location.port);
console.log(window.location.href);
console.log(window.location.protocol);//所使用的web协议
}
btn2.onclick = function(){
location.assign("http://www.baidu.com");//加载新的文档
}
</script>
</body>
</html>