1、基础准备:
先来了解下,如何运用js实现select动态添加option。
//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("文本","值")); //方法一: obj.options.add(new Option("text","value")); //方法二: for(var i=0;i<10;i++){ obj.options[i]=new Option("新文本","新值"); //方法三: } } //3.删除所有选项option function removeAll(){ var obj=document.getElementById('mySelect'); obj.options.length=0; } //4.删除一个选项option function removeOne(){ var obj=document.getElementById('mySelect'); var index=obj.selectedIndex; //index,要删除选项的序号 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); }
2、时间联动实战
demo:
时间联动的要点就是天数随月份变化,考虑闰年,口诀:四年一润,百年不润,四百年再润。 下面直接看代码吧。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="author" content="@my_coder"> <title>时间联动</title> </head> <body> <select id="year"> <option>请选择年份</option> </select> <select id="month"> <option>请选择月份</option> </select> <select id="day"> <option>请选择日</option> </select> </body> </html> <script type="text/javascript"> var y=document.getElementById("year"), m=document.getElementById("month"), d=document.getElementById("day"); //年 var year=new Date().getFullYear(); for(var i=year;i>=1990;i--){ y.options[year+1-i]=new Option(i,i); //第一个参数是option的文本值,第二个参数是option的value值 } //月 for(var i=1;i<=12;i++){ m.options[i]=new Option(i,i); } //日 var day = function(){ d.length=1; //初始化 var y_value=y.value, m_value=m.value; if(y_value==""||m_value==""){ return; } else{ var arr=[31,28,31,30,31,30,31,31,30,31,30,31]; if((y_value%4==0&&y_value%100!=0)||y_value%400==0){ arr[1]++; } for(i=1;i<=arr[m_value-1];i++){ d.options[i]=new Option(i,i); } } } y.onchange = function(){ day(); } m.onchange = function(){ day(); } </script>
原文地址:http://www.cnblogs.com/duanhuajian/archive/2013/06/09/3129365.html