Hi~,我是 一碗周,一个在舒适区垂死挣扎的前端,如果写的文章有幸可以得到你的青睐,万分有幸~
写在前面
通常在Web开发中,打开一个页面有两种方式,一种是使用location的href属性来打开一个页面;还有一种就是使用window对象下的open()方法。
接下来我们就来了解一下这两种方式的用法与区别。
location.href的用法
目前location.href大致有三种用法,具体如下:
在前面页面打开URL
location.href /* 或者 */ self.location.href window.location.href this.location.href /* 都是等价的 */在父页面打开URL
parent.location.href在顶层页面打开URL
top.location.href
仅仅看这些内容还是不够清晰明了,我们来看一下例子:
a.html
<body>
<h3>a.html</h3>
frameLabelStart--frameLabelEnd
</body>
b.html
<body>
<h3>b.html</h3>
frameLabelStart--frameLabelEnd
</body>
c.html
<body>
<h3>c.html</h3>
<button id="jump-current">本页跳转</button>
<button id="jump-parent">跳转至父级-parent</button>
<button id="jump-top">跳转至顶级-top</button>
</body>
<script>
let jumpCurrent = document.getElementById('jump-current')
let jumpParent = document.getElementById('jump-parent')
let jumpTop = document.getElementById('jump-top')
/* 跳转 */
// 当前页面
jumpCurrent.onclick = () => {
location.href = 'https://juejin.cn/user/3350967174838701/columns'
}
// 父级页面
jumpParent.onclick = () => {
parent.location.href = 'https://juejin.cn/user/3350967174838701/columns'
}
// 顶层页面
jumpTop.onclick = () => {
top.location.href = 'https://juejin.cn/user/3350967174838701/columns'
}
</script>
我们创建了3个HTML页面,这几个页面的关系是a.html嵌套的b.html嵌套着c.html。
运行结果图如下所示:

通过效果图对location.href几种方式的区别就一目了然了。
window.open的用法
window.open()方法用于打开一个新的浏览器窗口,该方法的语法结构如下:
window.open(strUrl, strWindowName, [strWindowFeatures])
strUrl:要在新打开的窗口中加载的URL。strWindowName:新窗口的名称。可选的参数如下
_blank:打开一个新的标签页。这个是默认值_parent:父页面打开_self:当期页面打开_top:顶层页面打开name:窗口名称
strWindowFeatures:这是一个可选参数,列出新窗口的特征。
示例代码如下:
<!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>open</title>
</head>
<body>
<button id="btn">打开</button>
</body>
<script>
let btn = document.getElementById('btn')
btn.onclick = () => {
window.open('https://juejin.cn/user/3350967174838701/columns', 'jueJin', `status`)
}
</script>
</html>
点击这个打开按钮会启动一个新的窗口,然后打开我们想要打开的URL。
location.href属性与window.open()方法的区别
Location.href属性与window.open()方法的区别如下所示:
Location.href属性是对当前浏览器窗口的URL地址对象的参考;window.open()方法打开一个新的窗口。Location.href属性一般用于页面的迭代,也就是重新定位当前页window.open()方法可以通过新开窗口或者说新开标签页打开一个网址,而location.href属性只能在当前页打开一个网址。
写在最后
虽然location.href属性与window.open()方法在开发的时候都可以用来做页面的跳转,但是两者的区别在某些时候还是有必要的区分的。