<!DOCTYPE html> <html> <head> <title>test</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> </head> <body> <script> function createSelect(s_id) { var mySelect = document.createElement("select"); mySelect.id = s_id; document.body.appendChild(mySelect); } function addOption(x_text, y_value, s_id) { var obj = document.getElementById(s_id); // obj.add(new Option(x_text, y_value)); // 创建方式1 obj.options[obj.options.length] = new Option(x_text, y_value); // 创建方式2 } //清除select选项 function removeAll(s_id) { var obj = document.getElementById(s_id); obj.options.length = 0; } //清除指定的option function removeOne(s_id, index) { var obj = document.getElementById(s_id); // obj.options.remove(index); // 清除方式1 obj.options[index] = null; // 清除方式2 } //清除选中的option function removeSelectOne(s_id) { var obj = document.getElementById(s_id); var s_index = obj.selectIndex; obj.options.remove(s_index); } //获得选项option的value值 text值 function getValue(s_id) { var obj = document.getElementById(s_id); var s_index = obj.selectedIndex; var s_value = obj.options[s_index].value; var s_text = obj.options[s_index].text; alert(s_value); alert(s_text); } function edit(s_id, index, x_text, y_value) { var obj = document.getElementById(s_id); obj.options[index] = new Option(x_text, y_value); } function removeSelect(s_id) { var mySelect = document.getElementById(s_id); mySelect.parentNode.removeChild(mySelect); } createSelect("mySelect"); addOption("文本1", "值1", "mySelect"); addOption("文本2", "值2", "mySelect"); addOption("文本3", "值3", "mySelect"); createSelect("mySelect2"); addOption("文本1", "值1", "mySelect2"); addOption("文本2", "值2", "mySelect2"); addOption("文本3", "值3", "mySelect2"); // removeAll("mySelect2"); // removeOne("mySelect",1); // removeSelectOne("mySelect"); // getValue("mySelect"); edit("mySelect",2,1,3); // removeSelect("mySelect2") </script> </body> </html>
HTML DOM remove() 方法
remove() 方法用于从下拉列表删除选项。
语法 selectObject.remove(index) 注意该element是select对象
该方法从选项数组的指定位置移除 <option> 元素。如果指定的下标比 0 小,或者大于或等于选项的数目,remove() 方法会忽略它并什么也不做。
了解几点:
获取某个form下的options数组 selectObject.options
options[x] 可以获取对应的 option;
创建一个新的option 方式 new Option(text,value)
option选项的value值 option[1].value 对应的显示文本值 option[1].text;