window中的location对象属性,保存了当前url的一些信息,URL(Uniform Resource Locator,统一资源定位符)的结构为:
protocol://host:port path (?query|#fragment)
protocol:协议类型,http/https/ftp等.
host:主机,如https://www.baidu.com中的www.baidu.com.
port:端口号,可省略,省略后一般有默认的端口号,比如http下是80.
path:路径.
?query:参数.
#fragment:片段,一般为链接或者锚点.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>location</title>
<script>
window.addEventListener('load', function() {
console.log(window.location);
});
</script>
</head>
<body>
</body>
</html>
location中有一些属性,可以获取到对应url中的部分内容:
href:获取到的是url的全部内容.
protocol:对应url中的protocol.
host:对应url中的host.
port:对应url中的port.
search:对应url中的query.
hash:对应url中的fragment.
我们可以通过改变location中的属性值来跳转页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>location</title>
<script>
window.addEventListener('load', function() {
location.host = 'www.baidu.com';
});
</script>
</head>
<body>
</body>
</html>
location中的方法:
assign(url):跳转到指定网页,可以后退到原页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>location</title>
<script>
window.addEventListener('load', function() {
let btn = document.querySelector('button');
btn.addEventListener('click', function() {
location.assign('https://www.baidu.com');
});
});
</script>
</head>
<body>
<button>assign</button>
</body>
</html>
replace(url):替换当前url,跳转新页面,不过这种方式会直接在历史记录中改变当前页面,不能后退到原页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>location</title>
<script>
window.addEventListener('load', function() {
let btn = document.querySelector('button');
btn.addEventListener('click', function() {
location.replace('https://www.baidu.com');
});
});
</script>
</head>
<body>
<button>replace</button>
</body>
</html>
reload(bool):刷新当前界面,参数可省略,默认为false,为true时为强制刷新:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>location</title>
<script>
window.addEventListener('load', function() {
let btn = document.querySelector('button');
btn.addEventListener('click', function() {
location.reload();
});
});
</script>
</head>
<body>
<button>reload</button>
</body>
</html>