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

ออบเจ็กต์ Base ใน HTML DOM

ออบเจ็กต์ Base (Base Object)

ออบเจ็กต์ Base ใน HTML DOM เกี่ยวข้องกับอิลิเมนต์ HTML <base> อิลิเมนต์ <base> ใช้ระบุ base URL สำหรับ URL ทั้งหมดที่เป็น relative ในเอกสาร HTML มีได้สูงสุด 1 อิลิเมนต์ <base> ต่อเอกสาร Base object ใช้ตั้งค่าหรืออ่านค่าแอตทริบิวต์ href ของ <base>

คุณสมบัติ (Properties)

คุณสมบัติ คำอธิบาย
hrefตั้งค่าหรือคืนค่าของแอตทริบิวต์ href ใน base element
targetตั้งค่าหรือคืนค่าของแอตทริบิวต์ target ใน base element

ไวยากรณ์ (Syntax)

การสร้าง base element

document.createElement("base")

การเข้าถึง base element

var a = document.getElementById("demoBase");

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

ตัวอย่างด้านล่างแสดงการสร้างและเข้าถึง <base> element

<!DOCTYPE html>
<html>
<body>
    <p>Create the element first and then access it</p>
    <p>Click the button below to create or access BASE element.</p>
    <button onclick="CreateBase()">CREATE</button>
    <button onclick="AcessBase()">ACCESS</button>
    <p id="SAMPLE"></p>
    <script>
        function CreateBase() {
            var x = document.createElement("BASE");
            x.setAttribute("id", "myBase");
            x.setAttribute("href", "https://www.google.com");
            document.head.appendChild(x);
            document.getElementById("SAMPLE").innerHTML = "BASE element with href https://www.google.com is created";
        }
        function AcessBase() {
            var x = document.getElementById("myBase").href;
            document.getElementById("SAMPLE").innerHTML = x;
        }
    </script>
</body>
</html>

ผลลัพธ์

เริ่มต้น: แสดงปุ่ม CREATE และ ACCESS

คลิก CREATE: สร้าง base element ใน head, href="https://www.google.com" แสดงข้อความยืนยัน

คลิก ACCESS: อ่านค่า href ของ base element แสดง "https://www.google.com/"

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

1. ฟังก์ชัน CreateBase()

function CreateBase() {
    var x = document.createElement("BASE");
    x.setAttribute("id", "myBase");
    x.setAttribute("href", "https://www.google.com");
    document.head.appendChild(x);
    document.getElementById("SAMPLE").innerHTML = "BASE element with href https://www.google.com is created";
}

2. ฟังก์ชัน AcessBase()

function AcessBase() {
    var x = document.getElementById("myBase").href;
    document.getElementById("SAMPLE").innerHTML = x;
}

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

  • <base> ต้องอยู่ใน <head> และมีได้ครั้งเดียวต่อเอกสาร
  • Base URL ใช้ resolve relative URLs: <a href="/page"> + <base href="https://site.com/"> = https://site.com/page
  • ถ้ามี <base> หลายตัว จะใช้ตัวแรกและละเว้นตัวถัดไป
  • Base element ไม่มี closing tag (void element)
  • การเปลี่ยน base.href แบบไดนามิกส่งผลต่อ relative URLs ที่สร้างหลังการเปลี่ยนแปลง