关于 select 的添加
option 应该注意的问题。
标准的做法如上
也就是说,标准的做法是
s.options.add();
但是如果你一定要用
s.a(option);
注意了,你只能用如下两种方式之一:
1.
s.a(option);
option.text = 'hello
world';
option.value =3;
也就是,一定要先添加到 select 中,然后再为 option 赋值。否则在 FF
下是显示正常的,但是在 IE6 中显示的是空白
2. 如果你要讲
option.text 和 option.value 的赋值放在前面,那么请用 option.innerHTML 而不是
option.text
如下:
option.innerHTML = 'hello world';
opion.value = 3;
option.a(option);
3
第三种解决方式。
var
op=document_createElement_x_x("option"); // 新建OPTION
(op)
op.setAttribute("value",0);
// 设置OPTION的
VALUE
op.a(document_createTextNode("请选择---"));
// 设置OPTION的 TEXT
select.a(op);
// 为SELECT 新建一
OPTION(op)
select.options.length=0;
//把select对象的所有option清除掉
select.options.remove(i);
//把select对象的第i个option清除掉
<
html>
<
head>
< meta
http-equiv="Content-Type" content="text/html;
charset=gb2312">
<
title>JS动态添加删除option< /title>
<
script>
//动态删除select中的所有options:
function
delAllOptions(){
document.getElementByIdx_x_x("user_dm").options.length=0;
}
//动态删除select中的某一项option:
function
delOneOption(indx){
document.getElementByIdx_x_x("user_dm").options.remove(indx);
}
//
动态添加select中的项option:
function
addOneOption(){
//document.getElementByIdx_x_x("user_dm").options.add(new
Option(2,"mytest"));
var
selectObj=document.getElementByIdx_x_x("user_dm");
;
selectObj.options[selectObj.length] = new
Option("mytest", "2");
}
<
/script>
<
/head>
<
body>
< select
id="user_dm" name="user_dm">
< option
value="0" selecte>==请选择人员==< /option>
< option
value="1">test< /option>
<
/select>< br>
< input
type="button" onClick="addOneOption()" value="添加">
< input
type="button" onClick="delOneOption(1)"
value="删除第一个">
< input
type="button" onClick="delAllOptions()" value="清空">
<
/body>
<
/html>
===============================================================================
<
html>
<
head>
< meta
http-equiv="Content-Type" content="text/html;
charset=gb2312">
<
title>Js动态添加与删除Option对象< /TITLE>
< script
language="JavaScript">
//
添加选项
function
addOption(pos){
var
objSelect=document.getElementByIdx_x_x("mySelect");
// 取得字段值
//var strName =
document.myForm.myOptionName.value;
// var strValue =
document.myForm.myOptionValue.value;
// 建立Option对象
var objOption = new
Option("李高灰","bbbbbbbbb");
if (pos == -1&& pos >
objSelect.options.length))
objSelect.options[objSelect.options.length] =
objOption;
else
objSelect.add(objOption, pos);
}
// 删除
function
deleteOption(type){
var
objSelect=document.getElementByIdx_x_x("mySelect");
if (type == true)
objSelect.options[objSelect.selectedIndex] =
null;
else
objSelect.remove(objSelect.selectedIndex);
}
//
显示选项信息
function
showOption(){
var
objSelect=document.getElementByIdx_x_x("mySelect");
var name =
objSelect.options[objSelect.selectedIndex].text;
var value =
objSelect.options[objSelect.selectedIndex].value;
;
}
//动态删除select中的所有options:
function
clearAllOptions(){
var
objSelect=document.getElementByIdx_x_x("mySelect");
objSelect.options.length=0;
}
<
/script>
原文转载至:http://www.cnblogs.com/apache-x/p/5458571.html