如何使用 jQuery 向 select 元素添加选项?
jqueryweb developmentfront end technology更新于 2026/1/12 14:37:17
要向 <select> 元素添加选项,您需要使用 append()。以下是 JavaScript 代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<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>
</head>
<body>
<select name="mySelection" id="selectCategory">
<option value="Book">Book</option>
<option value="TV">TV</option>
</select>
<script>
var mySelection = new Option("Mobile", "Samsung Mobile");
$(mySelection).html("Samsung Mobile");
$("#selectCategory").append(mySelection);
</script>
</body>
</html>
要运行上述程序,请保存文件名 anyName.html(index.html),然后右键单击该文件并选择在 VS Code 编辑器中使用实时服务器打开选项。
输出


