如何使用jQuery在选择元素中添加选项
在jQuery中,一个选项可以用3种方法添加到一个选择元素中。
方法1:将选项标签附加到选择框中
要添加的选项就像一个普通的HTML字符串一样被创建。选择框是用jQuery选择器选择的,这个选项是用append()方法添加的。append()方法将指定的内容作为jQuery集合的最后一个孩子插入。因此,该选项被添加到选择元素中。
语法:
$('#selectBox').append(`${optionText}`)
示例:
<!DOCTYPE html>
<html>
<head>
<title>
Adding options to a select element using jQuery?
</title>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
Adding options to a select element using jQuery?
</b>
Select one from the given options:
<select id="select1">
<option value="free">Free</option>
<option value="basic">Basic</option>
</select>
Click the button below to add
one option to the select box.
<button onclick="addOption()">
Add option
</button>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script type="text/javascript">
function addOption() {
optionText = 'Premium';
optionValue = 'premium';
('#select1').append(`<option value="{optionValue}">
${optionText}
</option>`);
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
方法2:使用Option()构造函数来创建一个新的选项
Option()构造函数被用来创建一个新的选项元素。一个新的选项被创建,选项的文本和值作为参数。然后用append()方法将这个元素添加到选择框中。
语法:
$('#selectBox').append(new Option(optionText, optionValue))
示例:
<!DOCTYPE html>
<head>
<title>Adding options to a select element using jQuery?</title>
</head>
<body>
<h1 style="color: green">GeeksForGeeks</h1>
<b>Adding options to a select element using jQuery?</b>
Select one from the given options:
<select id="select1">
<option value="free">Free</option>
<option value="basic">Basic</option>
</select>
Click the button below to add one option to the select box.
<button onclick="addOption()">Add option</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function addOption() {
optionText = 'Ultimate';
optionValue = 'ultimate';
$('#select1').append(new Option(optionText, optionValue));
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
方法3:用值和文本创建一个新的选项元素
一个新的jQuery DOM元素被创建为选项标签。标签的值是用val()方法设置的,选项的文本是用text()方法设置的。创建的元素然后用append()方法添加到选择框中。
语法:
$('#selectBox').append($('<option>').val(optionValue).text(optionText))
示例:
<!DOCTYPE html>
<head>
<title>Adding options to a select element using jQuery?</title>
</head>
<body>
<h1 style="color: green">GeeksForGeeks</h1>
<b>Adding options to a select element using jQuery?</b>
Select one from the given options:
<select id="select1">
<option value="free">Free</option>
<option value="basic">Basic</option>
</select>
Click the button below to add one option to the select box.
<button onclick="addOption()">Add option</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function addOption() {
optionText = 'Extra';
optionValue = 'extra';
('#select1').append(('<option>').val(optionValue).text(optionText));
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。