【JS】下拉框的基本操作


<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>


<body>
<select style="float:left;"name="scolor" id="scolor">
<option value="0">**請選擇**</option>
<option value="red">**紅色**</option>
<option value="green">**綠色**</option>
<option value="blue">**藍色**</option>
</select>
<div style="float:left;">
<ul >
<li type="1"><input type="button" value="添加一個選擇" οnclick="Test1();" /></li><br />
<li type="1"><input type="button" value="獲取選中項的索引" οnclick="Test2();" /></li><br />
<li type="1"><input type="button" value="獲取選中項的文本" οnclick="Test3();" /></li><br />
<li type="1"><input type="button" value="獲取選中項的值" οnclick="Test4();" /></li><br />
<li type="1"><input type="button" value="刪除選中項" οnclick="Test5();" /></li><br />
<li type="1"><input type="button" value="讓指定的項被選中" οnclick="Test6();" /></li><br />
<li type="1"><input type="button" value="修改選中項" οnclick="Test7();" /></li><br />
<li type="1"><input type="button" value="清空項" οnclick="Test8();" /></li><br />
<li type="1"><input type="button" value="替換" οnclick="Test9();" /></li><br />
</ul>
</div>

</body>
<script language="javascript" type="text/javascript">
function Test1(){
var scolor=document.getElementById("scolor");
scolor.options.add(new Option("**黃色**"));//選項的文本和值是一樣
//第二種方式
scolor.options.add(new Option("**橙色**","orange"));//添加指定文本和值的選項

}

function Test2(){
var scolor=document.getElementById("scolor");
alert(scolor.selectedIndex);
}

function Test3(){
var scolor=document.getElementById("scolor");
alert(scolor.options[scolor.selectedIndex].text);
}

function Test4(){
var scolor=document.getElementById("scolor");
//alert(scolor.options[scolor.selectedIndex].value);
alert(scolor.value);
}

function Test5(){
var scolor=document.getElementById("scolor");
scolor.options.remove(scolor.selectedIndex);
}

function Test6(){
var scolor=document.getElementById("scolor");
//scolor.selectedIndex=2;//控制索引
scolor.value="green";//控制值
}

function Test7(){
var scolor=document.getElementById("scolor");
scolor.options[scolor.selectedIndex]=new Option("**白色**","white");
}

function Test8(){
var scolor=document.getElementById("scolor");
/*
for(var i=0;i<scolor.options.length;i++){
scolor.options.remove(i);
}
remove只能刪除一次,無法刪除多個,使用循環也不行
*/
scolor.options.length=0;
}

//替換
function Test9(i){
var scolor=document.getElementById("scolor");
i=scolor.selectedIndex;
tem=scolor.options[i];
scolor.options.add(new Option(tem.text))
scolor.options[i]=new Option("**黑色**","black");

}
</script>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章