×

用JS向select选项框中添加新选项

作者:andyjiang2019.11.19来源:Web前端之家浏览:10407评论:0
关键词:jsselect

如何使用jQuery向select选项框中添加新选项,即如何向select元素中添加options元素?

方法1:将options标签添加到select元素中

先使用jquery选择器选择select元素,然后使用append()方法添加options标签元素。append()方法将指定的内容插入jQuery集合的最后一个子集合。这样options元素就被添加到select元素中。

语法:

$('#selectBox').append(`${optionText}`)

示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>如何使用jQuery向select元素中添加options?</title>
	</head>

	<body> 
    <h2 style="color: green"> 使用jQuery向select元素中添加options</h2> 
    <p> 
                    从给定选项中选择一个: 
        <select id="select"> 
            <option value="free">Free</option> 
            <option value="basic">Basic</option> 
        </select> 
    </p> 
    <p>单击下面的按钮,向选择框添加一个选项。</p> 
    
    <button onclick="addOption()">添加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'; 
  
            $('#select').append(`<option value="${optionValue}"> ${optionText} </option>`); 
        } 
    </script> 
</body> 
</html>

方法2:使用Option()方法创建新选项

Option()方法用于创建新的option元素。该方法将使用文本和选项的值作为参数创建一个新选项。然后使用append()方法将此option元素添加到选择框中。

语法:

$('#selectBox').append(new Option(optionText, optionValue))

示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>如何使用jQuery向select元素中添加options?</title>
	</head>

	<body> 
    <h2 style="color: red"> 使用jQuery向select元素中添加options</h2> 
    <p> 
                    从给定选项中选择一个: 
        <select id="select"> 
            <option value="hello">Hello</option> 
            <option value="hi">Hi</option> 
        </select> 
    </p> 
    <p>单击下面的按钮,向选择框添加一个选项。</p> 
    
    <button onclick="addOption()">添加option</button> 
    
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
    <script type="text/javascript"> 
        function addOption() { 
            optionText = 'welcome'; 
            optionValue = 'welcome'; 
  
            $('#select').append(new Option(optionText, optionValue)); 
        } 
    </script> 
</body> 
  
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/js82384092384920384.html

网友评论文明上网理性发言 已有0人参与

发表评论: