คุณสมบัติ href ของ Location
คุณสมบัติ href ของออบเจ็กต์ Location ใช้สำหรับคืนค่าหรือกำหนดค่าสตริงที่ตรงกับ URL ทั้งหมด (full URL) รวมถึง protocol, hostname, port, path, query string และ hash fragment
ไวยากรณ์ (Syntax)
การอ่านค่า href
location.href
การกำหนดค่า href
location.href = href
ตัวอย่างการใช้งาน
ตัวอย่างด้านล่างแสดงการใช้คุณสมบัติ Location href เพื่อดึงค่า URL ทั้งหมด
<!DOCTYPE html>
<html>
<head>
<title>Location href</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-href</legend>
<label for="urlSelect">URL ปัจจุบัน:</label>
<input type="url" size="30" id="urlSelect" value="https://www.example.com/aboutUs">
<input type="button" onclick="gethref()" value="Get href">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var urlSelect = document.getElementById("urlSelect");
function gethref() {
divDisplay.textContent = 'URL Path: ' + location.href;
}
</script>
</body>
</html>
ผลลัพธ์
ก่อนคลิกปุ่ม Get href จะแสดง URL ในช่องป้อนข้อมูล
หลังคลิกปุ่ม Get href จะแสดง URL ทั้งหมด (เช่น https://www.example.com/aboutUs)
คำอธิบายเพิ่มเติม
- คุณสมบัติ
hrefเป็นคุณสมบัติที่ครอบคลุมที่สุดของออบเจ็กต์ Location - เมื่อกำหนดค่า
location.href = "new-url"เบราว์เซอร์จะนำทางไปยัง URL ใหม่ทันที (เหมือนกับการคลิกลิงก์) - แตกต่างจาก
location.replace()ที่ไม่เก็บประวัติการนำทางใน history stack - สามารถใช้สร้าง URL ใหม่ได้โดยการต่อสตริง เช่น
location.href += "?page=2"