【问题标题】:Is there any difference between window.location and window.location.href? [duplicate]window.location 和 window.location.href 之间有什么区别吗? [复制]
【发布时间】:2011-06-07 09:15:08
【问题描述】:

可能重复:
Javascript: Setting window.location.href versus window.location

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

1

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

2

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

【问题讨论】:

  • @Tim 哦,我找不到。
  • 没问题的伙伴 - 有时值得先搜索你的问题 - 我刚刚在搜索中输入了你的标题,这是第一个结果。

标签: javascript


【解决方案1】:

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

但是,window.location 有几个其他属性可供您使用,例如 location.hostnamelocation.pathnamelocation.hash。所以你可以自己设置location.hash来改变哈希值。

【讨论】:

【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    window.location 是一个具有一些属性的对象,但 window.location.href 只是字符串。在 window.location 你有例如 reload 方法。

    【讨论】:

      猜你喜欢
      • 2016-09-05
      • 2013-06-10
      • 1970-01-01
      • 2012-05-28
      • 2010-12-24
      • 2015-11-22
      • 2015-02-23
      • 2018-07-15
      相关资源
      最近更新 更多