簡體   English   中英

JavaScript 中的 window.location.href 和 window.open () 方法

[英]window.location.href and window.open () methods in JavaScript

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

window.location.href不是一個方法,它是一個屬性,它會告訴你瀏覽器當前的 URL 位置。 更改屬性的值將重定向頁面。

window.open()是一種方法,您可以將 URL 傳遞給您想要在新 window 中打開的方法。 例如:

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.open將使用指定的 URL 打開一個新瀏覽器。

  • window.location.href將在其中調用代碼的 window 中打開 URL。

Note also that window.open() is a function on the window object itself whereas window.location is an object that exposes a variety of other methods and properties .

已經有一些答案描述了window.location.href屬性和window.open()方法。

我將 go 通過客觀使用:

1. 將頁面重定向到另一個

使用 window.location.href。 將 href 屬性設置為另一個頁面的 href。

2. 在新的或特定的 window 中打開鏈接。

使用 window.open()。 根據您的目標傳遞參數。

3.知道頁面的當前地址

使用 window.location.href。 獲取 window.location.href 屬性的值。 您還可以從 window.location object 中獲取特定的協議、主機名、哈希字符串。

有關詳細信息,請參閱位置 Object

window.open是一個方法; 您可以打開新的 window,並可以自定義它。 window.location.href 只是當前 window 的一個屬性。

window.open () will open a new window, whereas window.location.href will open the new URL in your current window.

window.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM