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

คุณสมบัติ length ของ HTML DOM Select

คุณสมบัติ length ของ HTML DOM Select ใช้สำหรับคืนค่าจำนวนองค์ประกอบ <option> ที่อยู่ภายในรายการแบบเลื่อนลง (drop-down list) ในเอกสาร HTML

รูปแบบไวยากรณ์ (Syntax)

object.length

ตัวอย่าง

ตัวอย่างการใช้งานคุณสมบัติ length ของ HTML DOM Select:

<!DOCTYPE html> <html> <head> <style>    html{       height:100%;    }    body{       text-align:center;       color:#fff;       background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;       height:100%;    }    p{       font-weight:700;       font-size:1.2rem;    }    .drop-down{       width:35%;       border:2px solid #fff;       font-weight:bold;       padding:8px;    }    .btn{       background:#0197F6;       border:none;       height:2rem;       border-radius:2px;       width:35%;       margin:2rem auto;       display:block;       color:#fff;       outline:none;       cursor:pointer;    }    .show{       font-size:1.5rem;       font-weight:bold;    } </style> </head> <body> <h1>ตัวอย่างคุณสมบัติ DOM Select length</h1> <p>สวัสดีครับ โปรดเลือกวิชาที่คุณชอบ:</p> <select class='drop-down'> <option>ฟิสิกส์</option> <option>คณิตศาสตร์</option> <option>เคมี</option> <option>ภาษาอังกฤษ</option> </select> <button onclick="showLength()" class="btn">คลิกเพื่อดูจำนวนตัวเลือก</button> <div class="show"></div> <script>    function showLength() {       var dropDown = document.querySelector(".drop-down");       var showMsg = document.querySelector(".show");       showMsg.innerHTML ="จำนวนตัวเลือก: " + dropDown.length;    } </script> </body> </html>

ผลลัพธ์

โค้ดด้านบนจะให้ผลลัพธ์ดังนี้:

คุณสมบัติ length ของ HTML DOM Select

คลิกที่ปุ่ม 「คลิกเพื่อดูจำนวนตัวเลือก」 เพื่อแสดงจำนวนตัวเลือกที่มีอยู่ในรายการแบบเลื่อนลง

คุณสมบัติ length ของ HTML DOM Select