Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

คุณสมบัติ hash ของ DOM Anchor: อ่าน/ตั้งค่า Anchor Part ของ URL

คุณสมบัติ anchor.hash คืออะไร?

คุณสมบัติ hash ของ HTMLAnchorElement (แท็ก <a>) ใช้สำห อ่าน/ตั้งค่าส่วน Anchor (Fragment Identifier) ของ URL** คือส่วนหลังเครื่องหมาย # รวม # ด้วย

ไวยากรณ์ (Syntax)

// อ่านค่า
var fragment = anchorElement.hash; // คืนค่า "#section1" หรือ ""

// ตั้งค่า
anchorElement.hash = "#section2"; // ต้องขึ้นต้นด้วย #

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<body>
  <h1>บริษัท</h1>
  <p><a id="mylink" href="https://www.example.com/abc/def.html#myteam">ทีมของเรา</a></p>
  <p>ดูส่วน Anchor ของลิงก์...</p>
  <h2 id="output"></h2>
  <button onclick="showHash()">แสดง Anchor Part</button>
  
  <script>
    function showHash() {
      var hash = document.getElementById("mylink").hash;
      document.getElementById("output").innerHTML = "Hash: " + hash;
    }
  </script>
</body>
</html>

ผลลัพธ์

กดปุ่ม "แสดง Anchor Part" → แสดง Hash: #myteam

URL Structure และ Hash

https://example.com/path/page.html?query=value#fragment
                    ↑           ↑           ↑
                 pathname    search      hash (anchor)
                 
hash = "#fragment" (รวม #)
ไม่มี fragment → hash = "" (Empty String)

คุณสมบัติ URL ของ Anchor (Location Object)

คุณสมบัติตัวอย่างคำอธิบาย
hrefFull URLURL เต็ม
protocol"https:"โปรโตคอล
host"example.com:8080"โฮสต์ + พอร์ต
hostname"example.com"โฮสต์อย่างเดียว
port"8080"พอร์ต
pathname"/path/page.html"พาธ
search"?query=value"Query String (รวม ?)
hash"#fragment"Anchor/Fragment (รวม #)
origin"https://example.com"Protocol + Host (Read-only)

การใช้งานจริง

  • Single Page Application (SPA) Routing: ใช้ Hash-based Routing (#/page)
  • Scroll to Element: location.hash = "#section-id"
  • Deep Linking: แชร์ลิงก์ไปยังส่วนเฉพาะของหน้า
  • State Management: เก็บ State ใน Hash (ไม่ส่งไป Server)