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

คุณสมบัติ type ของ Anchor ใน HTML DOM

คุณสมบัติ type ของ Anchor

คุณสมบัติ type ของ Anchor

คุณสมบัติ type ที่เกี่ยวข้องกับแท็ก anchor (<a>) ใช้สำหรับตั้งค่าหรืออ่านค่าของแอตทริบิวต์ type ของลิงก์ แอตทริบิวต์นี้เพิ่มเข้ามาใน HTML5 ใช้เพื่อแนะนำ MIME type ของทรัพยากรที่ลิงก์ไป ไม่บังคับ และเป็นข้อมูลช่วยเหลือ (advisory) เท่านั้น

ไวยากรณ์ (Syntax)

การอ่านค่า type

anchorObject.type

การกำหนดค่า type

anchorObject.type = MIME-type

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

ตัวอย่างด้านล่างแสดงการตั้งค่าและอ่านค่า type attribute

<!DOCTYPE html>
<html>
<body>
    <p><a id="Anchor" type="text/html" href="https://www.examplesite.com">example site</a></p>
    <p><a id="Anchor2" href="https://www.example.com">example</a></p>
    <p>Click the buttons to set and get the type attribute.</p>
    <button onclick="getType1()">GetType</button>
    <button onclick="setType2()">SetType</button>
    <p id="Type1"></p>
    <script>
        function getType1() {
            var x = document.getElementById("Anchor").type;
            document.getElementById("Type1").innerHTML = x;
        }
        function setType2() {
            document.getElementById("Type1").innerHTML = "Type has been set";
            document.getElementById("Anchor2").type = "text/html";
        }
    </script>
</body>
</html>

ผลลัพธ์

เริ่มต้น: ลิงก์แรกมี type="text/html", ลิงก์ที่สองไม่มี type

คลิก GetType: แสดง "text/html" (จากลิงก์แรก)

คลิก SetType: ตั้งค่า type ของลิงก์ที่สองเป็น "text/html" แล้วแจ้ง "Type has been set"

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

  • ค่า type เป็น MIME type เดียว (single MIME type) เช่น text/html, application/pdf, image/png, video/mp4
  • เป็นคำแนะนำ (advisory) เท่านั้น เบราว์เซอร์ไม่บังคับใช้ ตัว browser จะตรวจสอบ Content-Type header จาก server จริงๆ
  • มีประโยชน์สำหรับ: user agents, screen readers, prefetching, icons แสดงประเภทไฟล์
  • ไม่ส่งผลต่อการนำทางหรือการโหลดทรัพยากร
  • ใน HTML5 สามารถใช้กับ <a>, <link>, <source>, <embed>, <object>