js:History&location对象的back、go、reload方法&href属性

写案例的时候碰巧用到了,把用到的两个对象方法记一下

一、History对象

History 对象包含用户(在浏览器窗口中)访问过的 URL。

History 对象是 window 对象的一部分,可通过 window.history 属性对其进行访问。

属性:length -- 返回浏览器历史列表中的 URL 数量。

方法

back()

history.back():表示页面往后退一步,与单击后退按钮的执行操作一样

go()

history.go(参数number/url):加载历史列表中的某个具体的页面。

参数为正数,如go(1),表示页面向前走一步

参数为负数,如go(-1),表示页面后退一步

参数为字符串,如go(url),前往指定地址

如:window.history.go(1) //当前页面向前走一步

二、location对象

reload()方法

location.reload(): 重新载入当前文档(刷新当前页面)

如:window.location.reload()

href属性

返回一个完整的URL

location.href = url地址

如:window.location.href = 'http://www.baidu.com'

如:window.location.href = url.value 给到的字符串要有http://,不然会以一个字符串去拼接当前的url

三、举例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="button" value="前进" id="prev">
    <input type="button" value="后退" id="back">
    <input type="button" value="刷新" id="reload">
    <!-- url输入地址 -->
    <input type="text" id="url">
    <input type="button" value="跳转" id="go">
    <p>
        <input type="button" value="百度" id="baidu">
        <input type="button" value="新浪" id="xinlang">
    </p>
    <script>
        // 使用history对象和location对象
        //history 可以实现页面的跳转
        document.querySelector('#prev').addEventListener('click', () => {
            window.history.go(1) //history.go 表示网页往前走一个
        })
        document.querySelector('#back').addEventListener('click', () => {
            window.history.back() //history.back 表示网页往回走一个
        })
        document.querySelector('#reload').addEventListener('click', () => {
            window.location.reload() //location.reload() 刷新
        })
        //获取url地址
        let url = document.querySelector('#url')
        //给跳转按钮绑定事件
        document.querySelector('#go').addEventListener('click', () => {
            window.location.href = url.value
        })
        //给百度和新浪绑定
        document.querySelector('#baidu').addEventListener('click', () => {
            window.location.href = 'http://www.baidu.com'
        })
        document.querySelector('#xinlang').addEventListener('click', () => {
            window.location.href = 'http://www.sina.cn'
        })
    </script>
</body>

</html>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长风沛雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值