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);
}
整个实例的完整代码如下:
改进版:在select中添加、修改、删除option元素
function watch_ini(){ // 初始
for(var i=0; i
var word = document.createElement("OPTION");
word.text = arguments[i];
watch.keywords.add(word); // watch. is form name
}
}
function watch_add(f){ // 增加
var word = document.createElement("OPTION");
word.text = f.word.value;
f.keywords.add(word);
}
但上述 add() 方法只在IE下有效,为兼容FF和Opera,对上述代码进行了一下改进,改动后代码如下:
function watch_ini(){ // 初始
for(var i=0; i
var oOption=new Option(arguments[i],arguments[i]);
document.getElementById("MySelect")[i]=oOption;
}
}
function watch_add(f){ // 增加
var oOption=new Option(f.word.value,f.word.value);
f.keywords[f.keywords.length]=oOption;
}
整个实例的完整代码如下:
javascript select options text value
用一个字符串创建一个数组方法:
Neueste Artikel des Autors
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31