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

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

คุณสมบัติ selectedIndex ของ HTML DOM Select ใช้สำหรับคืนค่าและเปลี่ยนแปลงดัชนีของตัวเลือกที่ถูกเลือกในรายการแบบเลื่อนลงในเอกสาร HTML

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

  • การคืนค่า selectedIndex

object.selectedIndex
  • การเปลี่ยนแปลง selectedIndex

object.selectedIndex = “number”

ตัวอย่าง

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

<!DOCTYPE html> <html> <head> <style>    html{       height:100%;    }    body{       text-align:center;       color:#fff;       background: radial-gradient( circle farthest-corner at 23.1% 64.6%, rgba(129,125,254,1) 0%, rgba(111,167,254,1) 90% ) no-repeat;       height:100%;    }    p{       font-weight:700;       font-size:1.1rem;    }    .drop-down{       display:block;       width:35%;       border:2px solid #fff;       font-weight:bold;       padding:2px;       margin:1rem auto;       outline:none;    }    .btn{       background:orange;       border:none;       height:2rem;       border-radius:2px;       width:35%;       margin:2rem auto;       display:block;       color:#fff;       font-weight:bold;       outline:none;       cursor:pointer;    }    .show{       font-size:1.5rem;       font-weight:bold;    } </style> </head> <body> <h1>ตัวอย่างคุณสมบัติ DOM Select selectedIndex</h1> <p>สวัสดีครับ โปรดเลือกวิชาที่คุณชอบ:</p> <select class='drop-down' name="Drop Down List"> <option>ฟิสิกส์</option> <option>คณิตศาสตร์</option> <option>เคมี</option> <option>ภาษาอังกฤษ</option> <option>เศรษฐศาสตร์</option> <option>ภาษาฮินดี</option> <option>ชีววิทยา</option> </select> <button type="button" onclick="set()" class="btn">ตั้งค่า selectedIndex</button> <div class="show"></div> <script>    function set() {       var dropDown = document.querySelector(".drop-down");       document.querySelector(".show").innerHTML="ตั้งค่า selectedIndex = '3'";       dropDown.selectedIndex="3";    } </script> </body> </html>

ผลลัพธ์

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

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

คลิกปุ่ม 「ตั้งค่า selectedIndex」 เพื่อตั้งค่า selectedIndex='3' บนรายการแบบเลื่อนลง

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