class="area">
1.動態創建select
復制代碼代碼如下:
function createSelect(){
var mySelect = document.createElement("select");
mySelect.id = "mySelect";
document.body.appendChild(mySelect);
}
2.添加選項option
復制代碼代碼如下:
function addOption(){
//根據id查找對象,
var obj=document.getElementById('mySelect');
//添加一個選項
obj.add(new Option("文本","值")); //這個只能在IE中有效
obj.options.add(new Option("text","value")); //這個兼容IE與firefox
}
3.刪除所有選項option
復制代碼代碼如下:
function removeAll(){
var obj=document.getElementById('mySelect');
obj.options.length=0;
}
4.刪除一個選項option
復制代碼代碼如下:
function removeOne(){
var obj=document.getElementById('mySelect');
//index,要刪除選項的序號,這裡取當前選中選項的序號
var index=obj.selectedIndex;
obj.options.remove(index);
}
5.獲得選項option的值
復制代碼代碼如下:
var obj=document.getElementById('mySelect');
var index=obj.selectedIndex; //序號,取當前選中選項的序號
var val = obj.options[index].value;
6.獲得選項option的文本
復制代碼代碼如下:
var obj=document.getElementById('mySelect');
var index=obj.selectedIndex; //序號,取當前選中選項的序號
var val = obj.options[index].text;
7.修改選項option
復制代碼代碼如下:
var obj=document.getElementById('mySelect');
var index=obj.selectedIndex; //序號,取當前選中選項的序號
var val = obj.options[index]=new Option("新文本","新值");
8.刪除select
復制代碼代碼如下:
function removeSelect(){
var mySelect = document.getElementById("mySelect");
mySelect.parentNode.removeChild(mySelect);
}
整個實例的完整代碼如下:
復制代碼代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//ZH-CN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<head>
<script language=JavaScript>
function $(id)
{
return document.getElementById(id)
}
function show()
{
var selectObj=$("area")
var myOption=document.createElement("option")
myOption.setAttribute("value","10")
myOption.appendChild(document.createTextNode("上海"))
var myOption1=document.createElement("option")