Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính index của Option trong HTML DOM

Thuộc tính index của HTML DOM Option trả về và cho phép thay đổi vị trí chỉ số của một option trong tài liệu HTML.

Cú pháp

Cú pháp như sau:

  • Lấy index:

object.index
  • Thiết lập index:

object.index = “số"

Ví dụ

Dưới đây là ví dụ về thuộc tính index của HTML Option:

<!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>Demo DOM Option index</h1> <p>Chào bạn, hãy chọn môn học yêu thích:</p> <select class='drop-down' name="Drop Down List"> <option>Vật lý</option> <option>Toán học</option> <option>Hóa học</option> <option>Tiếng Anh</option> </select> <button onclick="showIndex()" class="btn">Hiển thị Index</button> <div class="show"></div> <script>    function showIndex() {       var dropDown=document.querySelector(".drop-down");       var showMsg=document.querySelector(".show");       showMsg.innerHTML="Chỉ số tùy chọn được chọn là: "+dropDown.options[dropDown.selectedIndex].index;    } </script> </body> </html>

Kết quả

Đoạn mã trên sẽ cho kết quả như sau:

Thuộc tính index của Option trong HTML DOM

Nhấn vào nút 「Hiển thị Index」 để hiển thị chỉ số của tùy chọn được chọn.

Thuộc tính index của Option trong HTML DOM