window.location.href
不是一个方法,而是一个属性,它将告诉您浏览器当前的URL位置。更改该属性的值将重定向页面。
window.open()
是一个方法,您可以通过它传递要在新窗口中打开的URL。例如:
window.location.href示例:
window.location.href = 'http://www.google.com'; //Will take you to Google.
window.open() 示例:
window.open('http://www.google.com'); //This will open Google in a new window.
window.open()
可以传递其他参数。请参考:window.open教程
window.location.href
是一个属性而不是方法,但是Internet Explorer(至少版本10)允许您将 href
当作方法来处理。我在我使用过的一个页面上看到它起作用了,只有在IE10中。这可能就是为什么提问者称 href
为一个方法的原因。请参见问题 IE incompatability with window.location.href。但是,在任何浏览器中使用 href
作为属性会更好,包括IE在内。 - Rory O'Kanewindow.location.href
,尽管不确定。毕竟,新版本的IE通常更加符合标准,而不是不符合。因此,如果IE10仍然破坏标准,那么旧版本可能也是如此。 - Rory O'Kanewindow.open(newUrl, '_self')
和 location.href = newUrl
有什么区别?两者都会在同一标签页中打开 newUrl
。 - Harrywindow.open
会打开一个带有指定URL的新浏览器。
window.location.href
会在调用代码所在的窗口中打开该URL。
请注意,window.open()
是window对象本身上的函数,而window.location
是一个公开了各种其他方法和属性的对象。
已经有答案介绍了 window.location.href 属性和window.open() 方法。
我将按照目标使用情况给出说明:
使用 window.location.href,将 href 属性设置为另一个页面的链接地址。
使用 window.open(),根据需要传递参数。
使用 window.location.href,获取 window.location.href 属性的值。您还可以从 window.location 对象中获取特定的协议、主机名和哈希字符串。
了解更多信息,请参阅 Location 对象。
window.open()
会打开一个新窗口,而window.location.href
会在当前窗口中打开新的URL。
window.open(newUrl, '_self')
和 location.href = newUrl
之间有什么区别? - Harrywindow.open
会在新的浏览器标签页中打开URL。
window.location.href
会在当前标签页中打开URL(你也可以使用location
)。
这里有一个示例代码(在SO片段中,window.open无法工作)。
var url = 'https://example.com';
function go1() { window.open(url) }
function go2() { window.location.href = url }
function go3() { location = url }
<div>Go by:</div>
<button onclick="go1()">window.open</button>
<button onclick="go2()">window.location.href</button>
<button onclick="go3()">location</button>