JavaScript動態(tài)操作select下拉框
相信在前端設計中必然不會少的了表單,因為經常會使用到下拉框選項,又或是把數據動態(tài)回顯到下拉框中。因為之前牽扯到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> <!-- 此處用于點擊動態(tài)添加到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.動態(tài)操作 - 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創(chuàng)建optgroup標簽 let optgroup=document.createElement("optgroup"); //設置optgroup標簽的label和id值 optgroup.label=obj.groupName; optgroup.id="optgroupId"+index; //把創(chuàng)建optgroup新增到select下 document.getElementById("mySelect1").add(optgroup); //針對optgroup標簽,添加它的option標簽 for (var i = 0; i < obj.optionName.length; i++) { //js創(chuàng)建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.動態(tài)新增 - 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
到此這篇關于JavaScript動態(tài)操作select下拉框的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- js實現省市區(qū)三級聯動非select下拉框版
- Vue.js仿Select下拉框效果
- js實現select下拉框選擇
- AngularJS動態(tài)生成select下拉框的方法實例
- 詳解vuejs2.0 select 動態(tài)綁定下拉框支持多選
- Ajax獲取php返回json數據動態(tài)生成select下拉框的實例
- vue.js select下拉框綁定和取值方法
- JavaScript實現獲取select下拉框中第一個值的方法
- 基于BootStrap multiselect.js實現的下拉框聯動效果
- js實現下拉框效果(select)
- JavaScript實現兩個select下拉框選項左移右移
- JavaScript實現向select下拉框中添加和刪除元素的方法
- JS Select下拉框(支持輸入模糊查詢)