JavaScript动态操作select下拉框_javascript技巧_

2022年4月17日08:35:14

相信在前端设计中必然不会少的了表单,因为经常会使用到下拉框选项,又或是把数据动态回显到下拉框中。因为之前牵扯到optgroup标签时遇到了问题,没查到太过详细的解决方案,自己动手操作记录一下。

首先就是咱们的老朋友"select"标签,因为需要js、jq两种操作,所以就定义两个select标签。

HTML代码:

<div style="width: 200px;height: 100px;margin: auto;margin-top: 100px;padding: 20px;background-color: pink;">
	<select id="mySelect1" style="width: 120px;"></select>
	<select id="mySelect2" style="width: 160px;"></select>
	<button id="addSelect2">添加</button> <!-- 此处用于点击动态添加到mySelect2 -->
</div>

之后就是引用jq,定义js、jq操作,代码我都贴下面了。

JS代码:

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
        //1.动态操作 - JS方式
        //这里先定义一个json对象,用于获取并新增到select标签
        let language={
	        "languageList":[
	        {
		    "groupName":"前端",
		    "optionName":[
			    {"languageName":"html"},
			    {"languageName":"CSS"},
			    {"languageName":"javascript"}
				],
	        },
	        {
		    "groupName":"后端",
		    "optionName":[
			    {"languageName":"java"},
			    {"languageName":"JSP"}
				]
	        }
	      ]
	    };
        //language.languageList - 数据位置
        let index=0;
        for (obj of language.languageList) {
	        //js创建optgroup标签
	        let optgroup=document.createElement("optgroup");
	        //设置optgroup标签的label和id值
	        optgroup.label=obj.groupName;
	        optgroup.id="optgroupId"+index;
                //把创建optgroup新增到select下
	        document.getElementById("mySelect1").add(optgroup);
	        //针对optgroup标签,添加它的option标签
	        for (var i = 0; i < obj.optionName.length; i++) {
		        //js创建option标签
		        let option=document.createElement("option");
		        option.value=obj.optionName[i].languageName;
		        option.innerHTML=obj.optionName[i].languageName;
		        document.getElementById("optgroupId"+index).appendChild(option);
	        }
	        index+=1; //自定义下标放在最后新增,防止添加option时id增加
        }
		
        //2.动态新增 - JQ方式
        let item=0;
        $("#addSelect2").click(function(){
	        item=item+1;
	        //jq点击按钮后向下拉框新增optgroup标签
	        $("#mySelect2").append("<optgroup id='optgroup"+item+"' label='生成的optgroup标签"+item+"'></optgroup>");
	        let r=Math.floor((Math.random()*5)+1); //生成随机数1-5
                //把随机数个数个的option添加到当前新增的optgroup下
	        for (var i = 1; i <= r; i++) {
		        $("#optgroup"+item).append(`<option value="`+i+`">随机生成的option`+i+`</option>`);
	        }
        });
</script>

需要注意的是:尽管用的id是递增产生的,但前面的名字也不要一样,我在测试按钮功能的时候,没注意就把两种optgroup的id定义成一样的,结果按钮随机生成的option都加到了相应id的mySelect1的optgroup里面了。

最后再贴一下运行效果

首先就是mySelect1回显json中的数据

点击添加按钮,新增到mySelect2

  • 作者:離人非淺  
  • 原文链接:https://www.cnblogs.com/7456Ll/p/16122748.html
    更新时间:2022年4月17日08:35:14 ,共 1996 字。