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

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

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

คุณสมบัติ username ที่เกี่ยวข้องกับแท็ก anchor (<a>) ใช้สำหรับตั้งค่าหรือคืนค่าส่วน username ของแอตทริบิวต์ href Username มักใช้คู่กับ password ในรูปแบบ username:password@hostname อยู่หลัง protocol และก่อน password

ไวยากรณ์ (Syntax)

การอ่านค่า username

anchorObject.username

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

anchorObject.username = UsernameValue

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

ตัวอย่างด้านล่างแสดงการเปลี่ยนและอ่านค่า username ของลิงก์

<!DOCTYPE html>
<html>
<body>
    <p><a id="Anchor" href="https://john:john123@www.examplesite.com">ExampleSite</a></p>
    <p>Click the button to change username</p>
    <button onclick="changeUser()">Set User</button>
    <button onclick="GetUser()">Get User</button>
    <p id="Sample"></p>
    <script>
        function changeUser() {
            document.getElementById("Anchor").username = "Rohan";
        }
        function GetUser() {
            var x = document.getElementById("Anchor").username;
            document.getElementById("Sample").innerHTML = x;
        }
    </script>
</body>
</html>

ผลลัพธ์

เริ่มต้น: ลิงก์มี username = "john"

คลิก Set User: เปลี่ยน username เป็น "Rohan"

คลิก Get User: แสดง username ปัจจุบัน (จะเป็น "Rohan" ถ้ากด Set User ก่อน)

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

  • รูปแบบ URL ที่มี credentials: protocol://username:password@hostname:port/path
  • คุณสมบัติ username และ password เป็นส่วนหนึ่งของ URL API (URLUtils)
  • คำเตือนด้านความปลอดภัย: ไม่ควรใส่ password จริงใน URL เพราะจะมองเห็นในประวัติ, logs, referrer headers
  • เบราว์เซอร์สมัยใหม่ลดการรองรับ credentials ใน URL ลง (security best practice)
  • คุณสมบัติที่เกี่ยวข้อง: password, href, origin, host, hostname, port