บทนำ
เมื่อทำงานกับแผนที่ภาพ (Image Map) ใน HTML โดยใช้แท็ก <area> บางครั้งเราต้องการดึงเฉพาะส่วนของแฮช (hash) จากแอตทริบิวต์ href เช่น about.htm#name โดย JavaScript มี property ชื่อ hash สำหรับวัตถุ HTMLAreaElement ที่ช่วยให้ทำได้ง่ายๆ
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<img src="/images/html.gif" alt="HTML Map" border="0" usemap="#html"/>
<map name="html">
<area id="myarea" shape="circle" coords="154,150,59"
href="about.htm#name" alt="Team" target="_self">
</map>
<script>
var x = document.getElementById("myarea").hash;
document.write("<br>Hash: " + x);
</script>
</body>
</html>
คำอธิบาย
- document.getElementById("myarea") - ค้นหา element area ที่มี id="myarea"
- .hash - property ที่คืนค่าส่วนแฮชรวมเครื่องหมาย # เช่น
"#name" - ผลลัพธ์จะแสดง:
Hash: #name
ข้อสังเกต
Property hash นี้เป็นส่วนหนึ่งของ URLUtils interface ที่ HTMLAreaElement สืบทอดมา ใช้งานได้ในเบราว์เซอร์สมัยใหม่ทุกตัว