Javascript 操作select是表单中常见的一种,下面介绍几种常用的JS动态操作select中的各种方法:// JavaScript Document<br>
<br>
//动态创建select <br>
function createSelect() <br>
{ <br>
var mySelect = document.createElement("select"); <br>
mySelect.id = "mySelect"; <br>
document.body.appendChild(mySelect); <br>
} <br>
<br>
//添加选项option <br>
function addOption() <br>
{ <br>
//根据id查找对象, <br>
var obj=document.getElementById('mySelect'); <br>
//添加一个选项 <br>
obj.add(new Option("文本","值")); //这个只能在IE中有效 <br>
obj.options.add(new Option("text","value")); //这个兼容IE与firefox <br>
} <br>
<br>
<br>
//删除所有选项option <br>
function removeAll() <br>
{ <br>
var obj=document.getElementById('mySelect'); <br>
obj.options.length=0; <br>
} <br>
<br>
<br>
//删除一个选项option <br>
function removeOne() <br>
{ <br>
var obj=document.getElementById('mySelect'); <br>
//index,要删除选项的序号,这里取当前选中选项的序号 <br>
var index=obj.selectedIndex; <br>
obj.options.remove(index); <br>
} <br>
<br>
//获得选项option的文本 <br>
var obj=document.getElementById('mySelect'); <br>
var index=obj.selectedIndex; //序号,取当前选中选项的序号 <br>
var val = obj.options[index].text; <br>
<br>
//修改选项option <br>
var obj=document.getElementById('mySelect'); <br>
var index=obj.selectedIndex; //序号,取当前选中选项的序号 <br>
var val = obj.options[index]=new Option("新文本","新值");
select.zip ( 675 B 下载:33 次 )
AD:真正免费,域名+虚机+企业邮箱=0元