window.location和window.location href之间有什么区别吗

Is there any difference between window.location and window.location.href?

本文关键字:window location 区别 什么 之间 href      更新时间:2023-09-26

可能重复:
Javascript:设置window.location.href与window.location

当我在浏览器中测试这些代码时,它们似乎是一样的。有什么不同吗?

1

window.location = "http://stackoverflow.com";

2

window.location.href = "http://stackoverflow.com";

是的,这是有区别的。CCD_ 1是CCD_ 2对象。window.location.href是位置的字符串表示。location对象的toString()值与href属性相同,因此如果用作字符串,它们是相同的。设置window.location与设置window.location.href相同。

但是,window.location还有其他几个可以使用的属性,例如window.location0、location.pathnamelocation.hash。因此,您可以自行设置location.hash来更改哈希值。

windows.location将一个项目添加到您的历史记录中,您可以(或应该能够)单击"返回"并返回当前页面。它是一个对象。

另一方面,windows.location.hrefwindow.location 的字符串表示

window.location是一个具有某些属性的对象,但window.location.href只是字符串。在window.location中,您可以使用例如reload方法。