<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>W3Cschool教程(w3cschool.cn)</title>
<script>
function insertBeforeSelected(){
var x=document.getElementById("mySelect");
if (x.selectedIndex>=0){
var option=document.createElement("option");
option.text="Kiwi";
var sel=x.options[x.selectedIndex];
try{
x.add(option,sel);
}catch(ex){
x.add(option,x.selectedIndex);
}
}
}
</script>
</head>
<body>
<form>
<select id="mySelect">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
<input type="button" onclick="insertBeforeSelected()" value="在选中项之前添加选项">
</form>
<p><b>贴士:</b>add()方法在IE8或更高版本中正常工作,要在页面中添加一个!DOCTYPE声明。对于IE 8之前的版本还要注意额外的代码。</p>
</body>
</html>