JavaScript的location对象和history对象

location对象

     location对象代表浏览器窗口中的地址栏,和window对象一样,无需特殊的创建方式,通过对象名就可使用,并调用其中的方法:

location.方法名();//或window . location.方法名();

 location对象中的方法及用法如下

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

实例

练习运用代码如下

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<input type="button" id="assign" value="assign" />
		<input type="button" id="reload" value="reload" />
		<input type="button" id="relace" value="relace" />
		<input type="button" id="href" value="href" />
		<script type="text/javascript">
			assign.onclick=function () {
				//assign():可以打开新的页面,并且可以返回,可以产生历史记录的
				location.assign("https://www.baidu.com")
			}
			reload.onclick=function () {
				//reload():实现的是页面刷新
				location.reload()
			}
			relace.onclick=function () {
				//replace():用新文档替换当前的文章,可以实现打开新的页面的功能,但不能返回,
				//故没有产生历史记录
				location.replace("https://www.baidu.com")
			}
			href.onclick=function () {
				location.href="https://www.baidu.com"
				console.log(location.host)
				console.log(location.hostname)
			}
		</script>
	</body>
</html>

history对象

history对象表示当前窗口的历史记录,同样通过对象名可以直接调用:

history.方法名();

history.属性名

//或

window.history.方法名();

window.history.属性名

 在history对象中,共有三个方法,它们分别为:

方法描述
back()加载当前窗口history列表中的前一个URL
forward()加载当前窗口history列表中的下一个URL。
go()加载当前窗口history列表中的某个具体页面。
  •  back ( )方法相当于后退按钮;
  • forward ()方法相当于前进按钮;
  • go(1代表前进1页,等价于forward( )方法;
  • go(-1)代表后退1页,等价于back( )方法;

实例

练习运用代码如下

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<input type="button" id="str" value="后退" />
		<input type="button" id="str2" value="跳转到3.html" />
		<input type="button" id="str3" value="forward" />
	    <input type="button" id="str4" value="go" />
		<script type="text/javascript">
			str.onclick=function () {
				history.back()//后退
			}
			str2.onclick=function () {
				location.href="3.html"
			}
			str3.onclick=function () {
				history.forward()
			}
			str4.onclick=function () {
				history.go()
			}
		</script>
	</body>
</html>

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<input type="button" value="后退" id="str">
		<input type="button" value="跳转到0809jsbom.html" id="str2">
		<script type="text/javascript">
			str.onclick=function () {
				history.back()
			}
			str2.onclick=function () {
				history.go(-1)
			}
		</script>
	</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值