基本操作
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> // 创建select function createSelect() { var mySelect = document.createElement("select"); mySelect.id = 'mySelect'; document.body.appendChild(mySelect); } createSelect(); // 添加option function addOption() { var objSelect = document.querySelector("#mySelect"); objSelect.add(new Option("文本1", "值1"));// ie objSelect.options.add(new Option("文本2", "值2"));// 文本是展示出来的内容 } addOption(); // 删除所有option function removeAllOption() { var objSelect = document.querySelector("#mySelect"); objSelect.options.length = 0; } // removeAllOption(); // 删除当前的option function removeNow() { var objSelect = document.querySelector("#mySelect"); var index = objSelect.selectedIndex; objSelect.options.remove(index); } removeNow(); // 获取当前option的内容 function getNow() { var objSelect = document.querySelector("#mySelect"); var index = objSelect.selectedIndex; var nowVal = objSelect.options[index].value;// objSelect.options[index].text console.log(nowVal);// 值2 } getNow(); // 修改当前option function modifyOption() { var objSelect = document.querySelector("#mySelect"); var index = objSelect.selectedIndex; objSelect.options[index]=new Option("新修改的","new"); } modifyOption(); // 删除select function removeSelect() { var objSelect = document.querySelector("#mySelect"); objSelect.parentNode.removeChild(objSelect); } removeSelect(); </script> </body> </html>
...