select标签设置默认选中的选项方法
方法有两种。
第一种通过
1 2 3
第二种为通过前端js来控制选中的项:
functionchange(){ document.getElementById("sel")[2].selected=true; } 1 2 3
获取
varval=document.all.Item.options[document.all.Item.selectedIndex].text vari=document.getElementById('sel').options[document.getElementById('sel').selectedIndex].value;
一些其它操作
1)动态创建select
functioncreateSelect(){ varmySelect=document.createElement("select"); mySelect.id="mySelect"; document.body.appendChild(mySelect); }
2)添加选项option
functionaddOption(){ //根据id查找对象, varobj=document.getElementById('mySelect'); //添加一个选项 obj.add(newOption("文本","值")); }
3)删除所有选项option
functionremoveAll(){ varobj=document.getElementById('mySelect'); obj.options.length=0; }
4)删除一个选项option
functionremoveOne(){ varobj=document.getElementById('mySelect'); //index,要删除选项的序号,这里取当前选中选项的序号 varindex=obj.selectedIndex; obj.options.remove(index); }
5)获得选项option的值
varobj=document.getElementById('mySelect'); varindex=obj.selectedIndex;//序号,取当前选中选项的序号 varval=obj.options[index].value;
6)获得选项option的文本
varobj=document.getElementById('mySelect'); varindex=obj.selectedIndex;//序号,取当前选中选项的序号 varval=obj.options[index].text;
7)修改选项option
varobj=document.getElementById('mySelect'); varindex=obj.selectedIndex;//序号,取当前选中选项的序号 varval=obj.options[index]=newOption("新文本","新值");
8)删除select
functionremoveSelect(){ varmySelect=document.getElementById("mySelect"); mySelect.parentNode.removeChild(mySelect); }
以上这篇select标签设置默认选中的选项方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。