如何使用 JavaScript 設定 location 和 location.href?


眾所周知,onclick 事件僅在使用者點選元素時發生,它是一個純 JavaScript 屬性。每當您點選 onclick 事件時,它都會執行一些操作,例如顯示訊息或將使用者重定向到另一個頁面。onclick 事件在網站中應儘量少用,因為它可能會造成使用者的困惑。因此,請明智地使用這些事件。

window.location 物件用於獲取當前頁面的 URL,並且它會將瀏覽器完全重定向到新頁面。它可以不帶字首編寫,即 window - 類似於 location.href、location 等。以下是 window location 的一些型別 -

  • location.href

  • location.hostname

  • location.protocol

  • location.assign()

  • location.pathname

在本文中,我們將學習如何使用 JavaScript 設定 location 和 location.href。

語法

以下是使用 JavaScript 在點選按鈕後設置 location 和 location.href 的語法 -

location = URL
or
location.href = URL

引數

  • URL - 用於指定 URL

步驟

按照以下步驟在 JavaScript 中點選按鈕後設置 location 和 location.href -

步驟 1 - 在 body 部分,我們定義了標題、按鈕和指令碼元素。

步驟 2 - 讓我們為 HTML 文件的標題元素定義樣式。

步驟 3 - 對於按鈕元素,定義了 myLocation() 方法。使用此方法,當我們按下按鈕時,位置將發生更改。

步驟 4 - 在 myLocation() 方法中,清楚地提到了應執行該方法功能的位置 URL。

步驟 5 - 點選按鈕後,將觸發 onClick 事件函式,並更改 URL 位置。

示例

在此示例中,我們將透過 JavaScript 在點選按鈕後設置位置。

<html>
   <body> 
      <h2>Setting the location using the Javascript</h2>
      <p>Click the button to go to www.tutorialspoint.com</p>
      <button onclick ="myLocation()">
         Click Here to go to the URL
      </button>

      <script>
         //function to setting the location using the Javascript 
         function myLocation() {
            location = "https://tutorialspoint.tw/";   
         }
      </script>
   </body>
</html>

示例

讓我們再看一個使用 location.href 透過 JavaScript 設定位置的示例。

<html> 
   <body> 
      <h2>Setting the location using the Javascript<h2>
      <button onclick ="hrefLocation()">
         Click Here to go to the Tutorials Point
      </button>
      <script>
         //function to setting the location using the Javascript 
         function hrefLocation() {
            location.href = "https://www.tutorix.com/index.htm";   
         }
      </script>
   </body>
</html>

結論

在本文中,我們演示瞭如何設定 location 和 location.href 以及示例。我們在這裡看到了兩個不同的示例,我們使用了 location 屬性來設定 URL 的位置。在第一個和第二個示例中,我們使用了“location 和 location.href”屬性來設定指定的 URL。

更新於: 2023年2月24日

4K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.