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

การใช้งาน Event onhashchange ใน JavaScript

Event onhashchange ทริกเกอร์เมื่อ Hash Fragment (ส่วนหลัง #) ของ URL เปลี่ยนแปลง ใช้สำหรับ SPA Routing, Deep Linking, In-page Navigation

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <body onhashchange="newFunc()">
    <button onclick="functionChange()">Click to change anchor</button>
    <script>
      function functionChange() {
        location.hash = "about";
        var hash = location.hash;
        document.write("The anchor part is now: " + hash);
      }
      function newFunc() {
        alert("Anchor part changed!");
      }
    </script>
  </body>
</html>

คำอธิบาย

  • location.hash — อ่าน/ตั้งค่า Hash Fragment (รวม #)
  • Event ทริกเกอร์เมื่อ User คลิก Anchor Link (<a href="#section">) หรือ JS เปลี่ยน location.hash
  • ไม่ Reload หน้า — เหมาะสำห SPA

รูปแบบมาตรฐานสมัยใหม่

window.addEventListener('hashchange', (e) => {
  console.log('Old URL:', e.oldURL);
  console.log('New URL:', e.newURL);
  console.log('New Hash:', location.hash);
  
  // Router Logic
  const route = location.hash.slice(1) || 'home';
  loadView(route);
});

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

  • SPA Routing แบบง่าย: Hash-based Routing (#/users/123)
  • Deep Linking: แชร์ Link ไป Section เฉพาะ
  • Tab/Accordion State: Sync UI กับ URL Hash
  • Analytics: Track Hash Navigation

Hash vs History API

FeatureHash RoutingHistory API
URL Format#/path/path (Clean)
Server Configไม่ต้อง Configต้อง Redirect ทุก Route → index.html
SEOแย่กว่าดีกว่า
Browser SupportIE8+IE10+