天天看点

window.loaction和window.history对象

  • location和history都是BOM对象。
  • location对象包含有关当前URL的信息
  • history对象包含用户(在浏览器窗口中)访问的URL

    location对象包含以下属性:

属性 描述
hash URL的锚部分
host URL的主机名和端口
hostname URL的主机名
href 完整的URL
pathname URL路径名。
port URL服务器使用的端口号
protocol URL协议
search URL的查询部分(例:get请求的参数部分)

location对象方法:

方法 描述
assign() 载入一个新的文档
reload() 重新加载当前文档
replace() 用新的文档替换当前文档

history对象有一个length属性以及以下方法:

方法 描述
back() 加载 history 列表中的前一个 URL
forward() 加载 history 列表中的下一个 URL
go() 加载 history 列表中的某个具体页面

调用不同的方法观察参数的变化

<body>
    <button onclick="goAAA()">goAAA</button>
    <button onclick="goBack()">goBack</button>
    <button onclick="forward()">forward</button>
</body>
<script>
    console.log(window.location)
    console.log(window.history)
    function goAAA() {
        window.location.hash = 'hhh'
        console.log(window.location)
        console.log(window.history)
    }
    function goBack() {
        window.history.back()
        console.log(window.location)
        console.log(window.history)
    }
    function forward() {
        window.history.forward()
        console.log(window.location)
        console.log(window.history)
    }
</script>
           

第一次打印:

window.loaction和window.history对象

点击goAAA后打印:

window.loaction和window.history对象

点击goBack后打印:

window.loaction和window.history对象

点击forward后打印:

window.loaction和window.history对象