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

คุณสมบัติ hash ของ Location ใน HTML DOM

คุณสมบัติ hash ของ Location

คุณสมบัติ hash ของออบเจ็กต์ Location ใช้สำหรับคืนค่าหรือผนวกค่าสตริง (anchor/fragment identifier) เข้าไปใน URL ส่วน anchor จะนำหน้าด้วยเครื่องหมาย # อัตโนมัติ

ไวยากรณ์ (Syntax)

การอ่านค่า hash

location.hash

การกำหนดค่า hash

location.hash = 'string'

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

ตัวอย่างด้านล่างแสดงการใช้คุณสมบัติ Location hash เพื่อตั้งค่าและอ่านค่า hash fragment

<!DOCTYPE html>
<html>
<head>
    <title>Location hash</title>
    <style>
        form { width: 70%; margin: 0 auto; text-align: center; }
        * { padding: 2px; margin: 5px; }
        input[type="button"] { border-radius: 10px; }
    </style>
</head>
<body>
    <form>
        <fieldset>
            <legend>Location-hash</legend>
            <label for="urlSelect">URL ปัจจุบัน:</label>
            <input type="url" size="27" id="urlSelect" value="https://www.example.com/">
            <input type="text" id="textSelect" placeholder="hash value...">
            <input type="button" onclick="setHashValue()" value="Go To URL">
            <div id="divDisplay"></div>
        </fieldset>
    </form>
    <script>
        var divDisplay = document.getElementById("divDisplay");
        var urlSelect = document.getElementById("urlSelect");
        var textSelect = document.getElementById("textSelect");
        function setHashValue() {
            if (textSelect.value !== '') {
                location.hash = textSelect.value;
                urlSelect.value += location.hash;
                divDisplay.textContent = 'Page loaded. Current URL active';
            } else {
                divDisplay.textContent = 'Please provide a hash value';
            }
        }
    </script>
</body>
</html>

ผลลัพธ์

ก่อนคลิกปุ่ม Go To URL จะแสดง URL พื้นฐานและช่องป้อนค่า hash

หลังคลิกปุ่ม Go To URL พร้อมใส่ค่า hash จะนำทางไปยัง anchor ที่ระบุ (เช่น https://www.example.com/#section1)

คำอธิบายเพิ่มเติม

  • คุณสมบัติ hash จะคืนค่ารวมเครื่องหมาย # เสมอ (เช่น #section1)
  • การเปลี่ยนแปลง hash ไม่ทำให้หน้าเว็บโหลดใหม่ (no page reload) เหมาะสำหรับ Single Page Applications (SPA)
  • สามารถใช้ร่วมกับ event hashchange เพื่อตรวจจับการเปลี่ยนแปลง hash
  • มักใช้สำหรับการนำทางภายในหน้า (in-page navigation) หรือเก็บสถานะแอปพลิเคชัน