Thuộc tính hash của đối tượng Location trả về hoặc thêm một giá trị chuỗi (phần anchor) vào URL. Phần anchor tự động được thêm tiền tố '#' và sau đó được nối vào URL.
Cú pháp
Lấy giá trị thuộc tính hash
location.hash
Thiết lập giá trị thuộc tính hash
location.hash = 'string'
Ví dụ
Dưới đây là ví dụ minh họa cho thuộc tính Location hash:
<!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 hiện tại:</label> <input type="url" size="27" id="urlSelect" value="https://www.example.com/"> <input type="text" id="textSelect" placeholder="giá trị hash..."> <input type="button" onclick="setHashValue()" value="Đi đến 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 = 'Trang đã tải. URL hiện tại đang hoạt động'; } else { divDisplay.textContent = 'Vui lòng cung cấp giá trị hash'; } } </script> </body> </html>
Kết quả
Ví dụ này sẽ cho kết quả sau:
Trước khi nhấn nút 'Đi đến URL':

Sau khi nhấn nút 'Đi đến URL' với giá trị hash đã thiết lập:
