3.2 Location

建立 practice/location.html 檔案來練習。

認識網址

http://localhost:5500/practice/location.html?a=value1&b=value2#other

使用 location 物件

location.html 的檔案內容如下:

<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <button type="button" id="btn1">重新整理網頁</button>
    <button type="button" id="btn2">導向到其它網址</button>
    <button type="button" id="btn3">觀察網址資訊</button>

    <script>

      var btn1 = document.getElementById("btn1");
      btn1.addEventListener("click", function(){
        location.reload();
      });

      var btn2 = document.getElementById("btn2");
      btn2.addEventListener("click", function(){
        location.href = "https://tw.yahoo.com";
      });

      var btn3 = document.getElementById("btn3");
      btn3.addEventListener("click", function(){
        // 取得網址資訊
        console.log(location);

        console.log("href: " + location.href);
        console.log("protocol: " + location.protocol);
        console.log("hostname: " + location.hostname);
        console.log("host: " + location.host);
        console.log("port: " + location.port);
        console.log("pathname: " + location.pathname);
        console.log("search: " + location.search);
        console.log("hash: " + location.hash);
      });
    </script>
  </body>
</html>

瀏覽 http://localhost:5500/practice/location.html?a=value1&b=value2#other 並觀察 console 中的輸出。以及各按鈕的作用。

取得網址參數的資訊

編輯 location.html 檔案,多一個按鈕:

<button type="button" id="btn4">取得網址參數資訊</button>

以及 JS 的部份(使用內建的 URLSearchParams ):

var btn4 = document.getElementById("btn4");
btn4.addEventListener("click", function(){

  var search_obj = new URLSearchParams(location.search);
  console.log(search_obj.get("a")); // value1
  
});

透過 new URLSearchParams() ,然後將 location.search 帶入,就可以再透過 .get() 來取得網址參數的資訊。

Last updated