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

คุณสมบัติ baseURI ใน HTML DOM

คุณสมบัติ baseURI (baseURI Property)

คุณสมบัติ baseURI ใน HTML DOM คืนค่า Base Uniform Resource Identifier (URI) ของเอกสาร คุณสมบัตินี้เป็นแบบอ่านอย่างเดียว (read-only) คืนค่าสตริงที่แทน base URI ของหน้าที่กำหนด

ไวยากรณ์ (Syntax)

node.baseURI

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

ตัวอย่างด้านล่างแสดงการดึง base URI ของเอกสาร

<!DOCTYPE html>
<html>
<body>
    <p>Click the button below to see the base URI of the document</p>
    <button onclick="BaseFunction()">BASE URI</button>
    <p id="Sample"></p>
    <script>
        function BaseFunction() {
            var x = document.baseURI;
            document.getElementById("Sample").innerHTML = x;
        }
    </script>
</body>
</html>

ผลลัพธ์

เริ่มต้น: แสดงปุ่ม BASE URI

คลิก BASE URI: แสดง base URI ของเอกสารปัจจุบัน (เช่น https://example.com/page.html)

คำอธิบายโค้ด

  1. ปุ่ม BASE URI: เรียกฟังก์ชัน BaseFunction()
  2. ฟังก์ชัน BaseFunction():
    function BaseFunction() {
        var x = document.baseURI;
        document.getElementById("Sample").innerHTML = x;
    }

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

  • document.baseURI เทียบเท่ากับ document.documentURI ในกรณีส่วนใหญ่
  • Base URI มาจาก: <base href="..."> tag ใน head, หรือ URL ของหน้าถ้าไม่มี base tag
  • ใช้สำหรับ resolve relative URLs (เช่น <img src="image.jpg"> จะ resolve จาก base URI)
  • เป็นคุณสมบัติของ Node interface ทุกโหนดมี baseURI ของตัวเอง
  • ใน HTML5 สามารถเข้าถึงได้จาก document.baseURI หรือ element.baseURI
  • มีประโยชน์เมื่อทำงานกับ relative paths ใน JavaScript