目录
Location
作用
window.location 对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。
备注
window 这个前缀使用时可以省略
常见属性
location.hostname 返回 web 主机的域名
location.pathname 返回当前页面的路径和文件名
location.port 返回 web 主机的端口 (8080)
location.protocol 返回所使用的 web 协议(http://、https://、file//)
location.href 属性返回当前页面的 URL。
实例
这里是我直接使用静态页面测试的,没有涉及到后台服务。
<!DOCTYPE html>
<html>
<body>
<script>
document.write(location.href+"<br>");//file:///Users/houbinbin/IT/OTHER/learn-book/JS/learn/code/html/location.html
document.write(location.hostname+"<br>"); //empty
document.write(location.pathname+"<br>");//Users/houbinbin/IT/OTHER/learn-book/JS/learn/code/html/location.html
document.write(location.port+"<br>"); //empty
document.write(location.protocol+"<br>"); //file
</script>
</body>
</html>
window.assign
location.assign() 方法加载新的文档。
- html
<!DOCTYPE html>
<html>
<body>
<script>
window.location.assign("https://www.github.com")
</script>
</body>
</html>
如果打开这个文件,其实和浏览 github 效果是一样的。
History
window.history 对象包含浏览器的历史信息
常用方法
history.back()
与在浏览器点击后退按钮相同
history.forward()
与在浏览器中点击按钮向前相同
例子
- history.html
<html>
<head>
<script>
function back(){
window.history.back()
}
function forward(){
window.history.forward()
}
</script>
</head>
<body>
<button onclick="back()">back</button>
<button onclick="forward()">forward</button>
</body>
</html>
备注
此处直接点击按钮是没有效果的。
因为是一个单独的页面,实际开发中多页面的返回/前进等十分有用。