📖
JavaScript - 網站程式設計
  • JavaScript - 網站程式設計
  • 1. 簡介
    • 1.1 講者簡介
    • 1.2 課程簡介
    • 1.3 開發工具簡介
  • 2. JS 在網頁上的基本觀念
    • 2.1 變數宣告
    • 2.2 資料型態
    • 2.3 基礎節點操控
    • 2.4 套用方式
  • 3. 瀏覽器物件模型 (BOM)
    • 3.1 Window
    • 3.2 Location
    • 3.3 內建彈出視窗
  • 4. 文件物件模型 (DOM)
    • 4.1 DOM 簡介
    • 4.2 取得節點、內容、屬性
    • 4.3 節點查找(Traversing)
    • 4.4 更新節點
    • 4.5 新增節點
    • 4.6 刪除節點、屬性
    • 4.7 操控 class 屬性
    • 4.8 練習
  • 5. 事件 (Events)
    • 5.1 事件(Event)簡介
    • 5.2 事件物件(Event Object)
    • 5.3 window 及 document 事件
    • 5.4 滑鼠相關事件
    • 5.5 鍵盤相關事件
    • 5.6 scroll 事件
    • 5.7 表單事件及停止元素預設行為
    • 5.8 動態事件綁定
    • 5.9 練習
  • 6. 表單 (Form)
    • 6.1 取得表單資料
    • 6.2 設定表單資料
    • 6.3 練習
  • 7. 儲存機制(Storage)
    • 7.1 Cookies
    • 7.2 localStorage
  • 8. ECMAScript (ES)
    • 8.1 Template String
    • 8.2 Arrow Function
    • 8.3 Spread and Rest Operator
    • 8.4 物件屬性簡寫
    • 8.5 解構賦值
  • 9. 作業
  • 10. 參考資料
Powered by GitBook
On this page
  • 認識網址
  • 使用 location 物件
  • 取得網址參數的資訊
  1. 3. 瀏覽器物件模型 (BOM)

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() 來取得網址參數的資訊。

Previous3.1 WindowNext3.3 內建彈出視窗

Last updated 2 years ago