要在jQuery的<select>
元素中添加選項(xiàng),您可以使用append()
或val()
方法。以下是兩種方法的示例:
方法1:使用append()
方法向<select>
元素添加選項(xiàng):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Add Option</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<select id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<button id="addButton">Add Option</button>
<script>
$("#addButton").click(function() {
$("#mySelect").append("<option value='newOption'>New Option</option>");
});
</script>
</body>
</html>
方法2:使用val()
方法向<select>
元素添加選項(xiàng)(此方法需要先將<select>
元素的值設(shè)置為空):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Add Option</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<select id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<button id="addButton">Add Option</button>
<script>
$("#addButton").click(function() {
$("#mySelect").val(''); // 清空現(xiàn)有選項(xiàng)
$("#mySelect").append("<option value='newOption'>New Option</option>");
});
</script>
</body>
</html>
在這兩個(gè)示例中,當(dāng)用戶點(diǎn)擊"Add Option"按鈕時(shí),將向<select>
元素添加一個(gè)新的選項(xiàng)。