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

รันสคริปต์เมื่อส่วน anchor ของ URL เปลี่ยนแปลงด้วย onhashchange

เหตุการณ์ onhashchange ทำงานเมื่อส่วน anchor (hash/fragment identifier) ของ URL เปลี่ยนแปลง คือส่วนที่ขึ้นต้นด้วย # เช่น #section1, #tab2 ใช้สำหรับ Single Page Applications (SPA) และการนำทางภายในหน้า

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

<!DOCTYPE html>
<html>
<body onhashchange="handleHashChange()">
  <h2>Demo onhashchange</h2>
  
  <nav>
    <a href="#home">หน้าแรก</a> |
    <a href="#about">เกี่ยวกับเรา</a> |
    <a href="#contact">ติดต่อเรา</a>
  </nav>
  
  <hr>
  
  <div id="content">
    <p>คลิกเมนูด้านบนเพื่อเปลี่ยน hash</p>
  </div>
  
  <p>Hash ปัจจุบัน: <span id="current-hash">#home</span></p>
  
  <script>
    function handleHashChange() {
      const hash = window.location.hash || '#home';
      document.getElementById('current-hash').textContent = hash;
      
      // แสดงเนื้อหาตาม hash
      const content = document.getElementById('content');
      switch(hash) {
        case '#about':
          content.innerHTML = '<h3>เกี่ยวกับเรา</h3><p>เราคือบริษัทเทคโนโลยี...</p>';
          break;
        case '#contact':
          content.innerHTML = '<h3>ติดต่อเรา</h3><p>อีเมล: contact@example.com</p>';
          break;
        default:
          content.innerHTML = '<h3>หน้าแรก</h3><p>ยินดีต้อนรับสู่เว็บไซต์ของเรา</p>';
      }
    }
    
    // เรียกตอนโหลดครั้งแรก
    handleHashChange();
  </script>
</body>
</html>

การใช้งานกับ JavaScript (Modern)

<script>
// แนะนำ: ใช้ addEventListener แทน inline handler
window.addEventListener('hashchange', (event) => {
  console.log('Hash changed from:', event.oldURL);
  console.log('Hash changed to:', event.newURL);
  console.log('New hash:', window.location.hash);
  
  // Router logic ที่นี่
  route(window.location.hash);
});

// ฟังก์ชัน router 簡單
function route(hash) {
  const routes = {
    '#home': () => showView('home'),
    '#about': () => showView('about'),
    '#contact': () => showView('contact'),
    '#user/': (id) => showUserProfile(id) // dynamic routes
  };
  
  // Simple matching
  for (const [pattern, handler] of Object.entries(routes)) {
    if (hash.startsWith(pattern)) {
      const param = hash.slice(pattern.length);
      handler(param);
      return;
    }
  }
  showView('404');
}
</script>

เหตุการณ์ที่เกี่ยวข้อง

เหตุการณ์ คำอธิบาย
hashchange Hash เปลี่ยนแปลง (ไม่รวมการโหลดครั้งแรก)
popstate History stack เปลี่ยน (back/forward buttons, history.pushState)
pageshow หน้าแสดง (รวม bfcache restore)

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

  • SPA routing แบบง่าย (hash-based routing)
  • Tab navigation ภายในหน้า
  • Deep linking ไปยังส่วนเฉพาะของหน้า
  • Tracking analytics เมื่อผู้ใช้เปลี่ยน section
  • State persistence ใน URL (filters, search queries)
เคล็ดลับ: สำหรับ SPA จริง แนะนำให้ใช้ History API (pushState, replaceState) ร่วมกับ popstate event แทน hash-based routing เพื่อ URL สวยงามและ SEO ดีกว่า