JS操作select和option常见⽤法1、获取选中select的value和text,html
<select id="mySelect">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
通过以下script代码s来获取选中的value和text
$("#mySelect").val(); //获取选中记录的value值
$("#mySelect option:selected").text(); //获取选中记录的text值
2、运⽤new Option("⽂本","值")⽅法添加选项option
var obj = ElementById("mySelect");
obj.add(new Option("4","4"));
3、删除所有选项option
var obj = ElementById("mySelect");
obj.options.length = 0;
4、删除选中选项option
var obj = ElementById("mySelect");
var index = obj.selectedIndex;
ve(index);
5、修改选中选项option
var obj = ElementById("mySelect");
var index = obj.selectedIndex;
obj.options[index] = new Option("three",3); //更改对应的值
obj.options[index].selected = true; //保持选中状态
6、删除select
var obj = ElementById("mySelect");
veChild(obj); //移除当前对象
7、select选择的响应事件
$("#mySelect").change(function(){ //添加所需要执⾏的操作代码})
1.动态创建select
function createSelect(){
var mySelect = ateElement_x("select");
mySelect.id = "mySelect";
document.body.appendChild(mySelect);
}
2.添加选项option
function addOption(){
//根据id查对象,
var ElementByIdx_x('mySelect');
//添加⼀个选项
obj.add(new Option("⽂本","值")); //这个只能在IE中有效
obj.options.add(new Option("text","value")); //这个兼容IE与firefox
}
3.删除所有选项option
function removeAll(){
var ElementByIdx_x('mySelect');
obj.options.length=0;
}
4.删除⼀个选项option
function removeOne(){
var ElementByIdx_x('mySelect');
//index,要删除选项的序号,这⾥取当前选中选项的序号
var index=obj.selectedIndex;
ve(index);
}
5.获得选项option的值
var ElementByIdx_x('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号var val = obj.options[index].value;
6.获得选项option的⽂本
var ElementByIdx_x('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号var val = obj.options[index].text;
7.修改选项option
var ElementByIdx_x('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号var val = obj.options[index]=new Option("新⽂本","新值"); 8.删除select
function removeSelect(){js教程removechild
var mySelect = ElementByIdx_x("mySelect"); veChild(mySelect);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。