【问题标题】:window.location.href and window.open () methods in JavaScriptJavaScript 中的 window.location.href 和 window.open() 方法
【发布时间】:2011-10-28 00:17:15
【问题描述】:

JavaScript 中的window.location.hrefwindow.open () 方法有什么区别?

【问题讨论】:

标签: javascript location window href window-object


【解决方案1】:

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 tutorial

【讨论】:

  • 标准可能确实说window.location.href 是一个属性,而不是一个方法,但是Internet Explorer(至少版本10)也允许您将href 视为一种方法。我已经在我使用过的一页上看到它仅在 IE10 中有效。这可能就是提问者调用href 方法的原因。请参阅问题IE incompatability with window.location.href。但是,是的,最好使用href 作为属性,它可以在任何浏览器中使用,including IE
  • @RoryO'Kane,这个问题是在 2011 年提出的。我怀疑用户指的是 IE 10。
  • 是的。但我认为,尽管不确定,旧版本的 IE 很可能会以同样的方式处理 window.location.href。毕竟,较新版本的 iE 通常会更多基于标准,而不是更少。因此,如果 IE10 仍在打破标准,那么旧版本可能也会这样做。
  • 使用 window.open(newUrl, '_self') 和 location.href = newUrl` 有什么区别?两者都会在同一个标​​签中打开newUrl
【解决方案2】:
  • window.open 将打开具有指定 URL 的新浏览器。

  • window.location.href 将在调用代码的窗口中打开 URL。

还要注意window.open() 是窗口对象本身的函数,而window.location 是公开各种other methods and properties 的对象。

【讨论】:

    【解决方案3】:

    已经有描述window.location.href属性和window.open()方法的答案。

    我会按客观用途去:

    1。将页面重定向到另一个页面

    使用 window.location.href。将 href 属性设置为另一个页面的 href。

    2。在新窗口或特定窗口中打开链接。

    使用 window.open()。根据您的目标传递参数。

    3。知道页面的当前地址

    使用 window.location.href。获取 window.location.href 属性的值。您还可以从 window.location 对象中获取特定的协议、主机名、哈希字符串。

    更多信息请参见Location Object

    【讨论】:

      【解决方案4】:

      window.open 是一个方法;您可以打开新窗口,并可以自定义它。 window.location.href 只是当前窗口的一个属性。

      【讨论】:

        【解决方案5】:

        window.open () 将打开一个新窗口,而window.location.href 将在当前窗口中打开新 URL。

        【讨论】:

        • window.open() 如果'_self'作为附加参数传递,也可以在同一个窗口中打开'url'。
        • 是的,有同样的疑问。使用 window.open(newUrl, '_self') 和 location.href = newUrl` 有什么区别?
        【解决方案6】:

        window.open 将在新浏览器选项卡中打开 url

        window.location.href 将在当前选项卡中打开 url(您可以使用 location

        这里是example fiddle(在 SO sn-ps 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>

        【讨论】:

          猜你喜欢
          • 2013-09-09
          • 1970-01-01
          • 2019-08-13
          • 2011-06-16
          • 1970-01-01
          • 2010-09-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多