【JS】下拉框的基本操作

19 篇文章 0 订阅


<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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值