如何使用 jQuery 填充選擇列表?
要使用 jQuery 填充選擇列表,請使用 for 迴圈以及 append(),並將選項追加到已建立的選擇項。
假設我們有以下選擇和選項:
<select id="customerNameList" name="customer"> <option value="John">John</option> <option value="David">David</option> </select>
示例
以下是使用 append() 追加更多選項的程式碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=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> <body> <select id="customerNameList" name="customer"> <option value="John">John</option> <option value="David">David</option> </select> </body> <script> $(document).ready(function () { var data = [ { "name": "Bob", "customerName": "Bob" }, { "name": "Mike", "customerName": "Mike" } ]; for (var index = 0; index <= data.length; index++) { $('#customerNameList').append('<option value="' + data[index].name + '">' + data[index].customerName + '</option>'); } }); </script> </html>
要執行上述程式,請將檔名儲存為 anyName.html(index.html)。右鍵單擊該檔案,然後在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。
輸出
輸出如下:
廣告