JavaScript獲取select選項(下拉選單)的長度?
比方說,下面是從我們的下拉選單(選擇) −
<select id="lengthListOfOptionDemo"> <option>John</option> <option>Mike</option> <option>Sam</option> <option>David</option> <option>Carol</option> </select>
以下是獲取JavaScript中列表選項長度的程式碼 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale= 1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/ 4.7.0/css/font-awesome.min.css"> <style> </style> <body> <select id="lengthListOfOptionDemo"> <option>John</option> <option>Mike</option> <option>Sam</option> <option>David</option> <option>Carol</option> </select> <script> var lengthOfListOptions = $("#lengthListOfOptionDemo option").length; console.log("The length is=" + lengthOfListOptions); </script> </body> </html>
要執行上面的程式,請儲存檔名為“anyName.html(index.html)”並右鍵單擊該檔案。在VS Code編輯器中選擇“Open with Live Server”選項。
輸出
這將產生以下輸出 −
廣告