如何用 jQuery 刪除下拉框中的所有選項,然後新增一個選項並選中它?


若要刪除,請使用 remove() 並使用 append() 在已建立的下拉列表中新增選項。假設我們的下拉列表為以下內容 −

<select id="demo">
   <option value="JavaScript">JavaScript</option>
   <option value="MySQL">MySQL</option>
</select>

示例

以下為刪除所有選項並新增一個新選項的程式碼 −

 即時演示

<!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="demo">
      <option value="JavaScript">JavaScript</option>
      <option value="MySQL">MySQL</option>
   </select>
</body>
<script>
   $('#demo')
   .find('option')
   .remove()
   .end()
   .append('<option value="MongoDB">MongoDB</option>')
   .val('MongoDB')
   ;
</script> 
</html>

若要執行上述程式,請將檔名儲存為 anyName.html(index.html)。右鍵單擊檔案,然後選擇 VS 程式碼編輯器中的“使用 Live Server 開啟”選項。

輸出

輸出如下 −

更新於: 03-Oct-2020

664 次瀏覽

開啟您的 職業

完成課程認證

開始
廣告
© . All rights reserved.