先来了解下,如何运用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、时间联动实战
时间联动的要点就是天数随月份变化,考虑闰年,口诀:四年一闰,百年不闰,四百年再闰。
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="utf-8" /> 6 7 <title>日期和年份月份联动demo</title> 8 9 </head> 10 11 <body> 12 <select id="year"> 13 <option value="">请选择年份</option> 14 </select> 15 <select id="month"> 16 <option value="">请选择月份</option> 17 </select> 18 <select id="day"> 19 <option value="">请选择日期</option> 20 </select> 21 <script> 22 var year = document.getElementById("year"); 23 var month = document.getElementById("month"); 24 var day = document.getElementById("day"); 25 var y = new Date().getFullYear(); 26 //前后均有 27 for (i = (y - 30); i < (y + 30); i++) { 28 year.options.add(new Option(i + "年", i)); 29 //格式不要写错,不要写成add(new Option(i + "年"), i)。 30 } 31 //只写前或者后 32 // for(var i=y;i>1977;i--){ 33 // year.options[y+1-i]=new Option(i+"年",i);//索引是options[],增加是new option(text,value) 34 // } 35 for (i = 1; i < 13; i++) { 36 month.options.add(new Option(i + "月", i)); 37 } 38 39 var d = function () { 40 day.length = 1; //初始化 41 if (year.value == " " || month.value == " ") { 42 return; 43 } else { 44 var Days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 45 if ((year.value % 4 == 0 && year.value % 100 != 0) || year.value % 400 == 0) { 46 Days[1]++; //判断为闰年,二月天数加一 47 } 48 for (i = 1; i <= Days[month.value - 1]; i++) { 49 day.options.add(new Option((i + "日"), i)); 50 } 51 } 52 } 53 //刷新日期天数 54 year.onchange = function () { 55 d(); 56 } 57 month.onchange = function () { 58 d(); 59 } 60 </script> 61 </body> 62 63 </html>