用原生的方法對select標簽的增刪操作
1、選中某一個option,一般采用 option[i].selected = true
2、添加option首先需要創建一個option的節點,然后插入到select,下面介紹了兩種辦法add(new Option)和document.createElement("option")
3、刪除option節點,下面介紹三種方法removeChild()、或者直接設置節點為null或者采用remove的方法循環刪除節點
<select id="select"> <option value="1">1</option> <option value="2">2</option> </select> <button onclick="AddOption()">添加子項目</button> <button onclick="newOption()">添加子項目</button> <button onclick="onOption()">選中子項目</button> <button onclick="removeOption()">刪除子項目</button> <button onclick="nulloption()">刪除子項目</button> <select id="select1"> <option value="1">1</option> <option value="2">2</option> </select> <button onclick="clearSelectboxMain()">刪除子項目</button> <script> var i = document.getElementById("select"); var j = document.getElementById("select1"); function clearSelectboxMain() { clearSelectbox(j); } function onOption() { i.options[1].selected = true; //選中第二個 } //添加 function AddOption() { i.add(new Option(3, 3), undefined); //添加選項,第二個參數為undefined是為了兼容IE和支持DOM的瀏覽器 } function newOption() { var newOption = document.createElement("option"); newOption.appendChild(document.createTextNode("4")); newOption.setAttribute("value", 4); i.appendChild(newOption); } //清除 function removeOption() { i.removeChild(i.options[0]); //移除子項目的方法 } function nulloption() { i.options[2] = null; //將子項目設置為空 } function clearSelectbox(selectbox) { for (var i = 0, len = selectbox.options.length; i < len; i++) { selectbox.remove(i); } } </script>