本文详细解析JavaScript中window.location.href的多种用法,包括当前页跳转、刷新及关闭窗口等操作。对比分析了window.location与window.open在功能、参数及iframe框架下的行为差异,并提供实际代码示例,帮助开发者准确选择页面导航方案。
一、前言
window.location.href 是获取当前页面 URL 或实现浏览器跳转到新 URL 的关键方法,属于 window.location 对象的属性。该属性返回表示当前页面 URL 的字符串;此外,通过向 window.location.href 赋值新的 URL,可以触发浏览器跳转到指定地址。
二、常见用例
- self.location.href="/url":在当前页面打开指定 URL 页面
- location.href="/url":在当前页面打开指定 URL 页面
- window.location.href="/url":在当前页面打开指定 URL 页面,上述三种写法效果相同。
- this.location.href="/url":在当前页面打开指定 URL 页面
- parent.location.href="/url":在父级页面中打开新页面
- top.location.href="/url":在顶层页面中打开新页面
- 若页面中包含自定义 frame,可将 parent、self 或 top 替换为自定义 frame 的名称,效果是在该 frame 窗口内打开指定的 URL 地址。
- window.location.href=window.location.href 与 window.location.Reload() 均可用于刷新当前页面。
两者的区别在于处理提交数据的方式不同。当存在提交数据时,window.location.Reload() 会提示用户是否重新提交数据,而 window.location.href=window.location.href 则是直接向指定的 URL 提交数据。
- 若需关闭当前窗口并在新窗口中打开某个链接:
var a = document.createElement('a')
a.setAttribute('href', href)
a.setAttribute('target', '_blank')
a.setAttribute('id', 'startTelMedicine')
a.onclick = function () {
//关闭窗口的方法
window.opener = null
window.open('', '_self', '')
window.close()
}
// 防止反复添加
if (document.getElementById('startTelMedicine')) {
document.body.removeChild(document.getElementById('startTelMedicine'))
}
document.body.appendChild(a)
a.click()- 如果无法关闭当前弹窗,可能存在父节点,可尝试使用:window.parent.close();
三、window.location.href和window.open的区别
1、window.location 是 window 对象的属性,而 window.open 是 window 对象的方法。window.location 是对当前浏览器窗口 URL 地址对象的引用;window.open 则是用于打开新窗口的函数。
2、window.open 不一定总是打开新窗口。如果指定窗口的名称与 window.open 中第二个参数一致,则该窗口会被替换。利用这一特性,可以在 iframe 和 frame 中替代 location.href 的使用。例如:
<iframe name="aa"></iframe>
<input type=button onclick="window.open('1.htm','aa','')">和
<input type=button
onclick="self.frames['aa'].location.href='1.htm'">上述两种写法效果相同。
3、在为按钮、表格、单元格、下拉列表和 DIV 等元素创建链接时,通常需要使用 JavaScript 来实现。与普通链接类似,有时需要让链接页面在当前窗口打开,有时则需要在新窗口打开,此时可使用以下两种方法之一:
window.open 用于打开新窗口;window.location 用于替换当前页,即重新定位当前页。可通过以下两个实例进行测试。
<input type="button" value="新窗口打开" onclick="window.open('http://www.google.com')">
<input type="button" value="当前页打开" onclick="window.location='http://www.google.com/'"> 4、如何指定 window.location 或 window.open 的 target?这是使用 frame 框架时常见的问题。解决方法如下:
window.location 改为 top.location 即可在顶部链接到指定页 或者
window.open("你的网址","_top"); 5、window.open 用于打开新窗口;window.location 用于替换当前页,即重新定位当前页。
用户无法更改 document.location(因为这是当前显示文档的位置)。window.location 本身也是一个对象。
但是,可以使用 window.location 来改变当前文档(用其他文档取代当前文档),而 document.location 不是对象。服务器重定向后,document.url 可能会发生变化,但 window.location.href 始终指向访问该网页时使用的原始 URL。大多数情况下,document.location 和 location.href 是相同的,但在存在服务器重定向时,document.location 包含已装载的 URL,而 location.href 包含原始请求文档的 URL。
6、window.open() 可以在一个网站中打开另一个网站的地址;而 window.location() 只能在当前网站中打开本网站的网页。
到此这篇关于 javascript 中 window.location.href 的用法 的文章就介绍到这了,更多相关 javascript window.location.href 内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!