JS select对象

使用select对象添加、删除option。

语法:selectObject.add(option,before)

option 必需,要添加的选项,必需是 option 或 optgroup 元素。
before 必需,将要添加的选项添加到该选项之前。如果该参数是null,就添加到选项数组的末尾。

 

<html>
<head>
<script type="text/javascript">
//添加option
function addOption(){
/*
//使用添加元素的方式添加
var op=document.createElement("option");
var opV=document.createTextNode("666");
op.appendChild(opV);
//添加到最后
document.getElementById("sel").appendChild(op);
//添加到指定位置
document.getElementById("sel").insertBefore(op,document.getElementById("op1"));
*/
//使用select对象自身的方法添加
var sel = document.getElementById("sel");
var opt = document.createElement("option");
opt.text="777";
if(sel.selectedIndex>=0){//表示有选定位置
	try{
		sel.add(opt,sel.options[sel.selectedIndex]);//标准情况,指定是那个option对象
	}catch(e){
		sel.add(opt,sel.selectedIndex);//IE,指定option的位置即可
	}
}else{//表示没有选定位置,那么就添加到最后
	try{
		sel.add(opt,null);//标准情况
	}catch(ex){
		sel.add(opt);//IE
	}
}
}

//删除option
function removeOption(){
	var sele = document.getElementById("sel");
	//删除第一个option
	//sele.remove(0);

	//删除最后一个option
	//sele.remove(sele.length-1);

	//删除指定的option
	sele.remove(sele.selectedIndex);
}
</script>
</head>
<body>
<select id="sel" size="10" >
<option id="op1">111</option>
<option>222</option>
<option>333</option>
<option>444</option>
<option>555</option>
</select>
<input type="button" value="addOption" onclick="addOption()" />
<input type="button" value="removeOption" onclick="removeOption()"/>
</body>
</html>

 

你可能感兴趣的:(js,select对象,selectedIndex)