首页 > 代码库 > new Option()——实现时间联动
new Option()——实现时间联动
1、基础准备:
先来了解下,如何运用js实现select动态添加option。
//1.动态创建selectfunction createSelect(){ var mySelect = document.createElement("select"); mySelect.id = "mySelect"; document.body.appendChild(mySelect);}//2.添加选项optionfunction 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.删除所有选项optionfunction removeAll(){ var obj=document.getElementById(‘mySelect‘); obj.options.length=0;}//4.删除一个选项optionfunction 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.修改选项optionvar obj=document.getElementById(‘mySelect‘);var index=obj.selectedIndex; var val = obj.options[index]=new Option("新文本","新值");//8.删除selectfunction removeSelect(){ var mySelect = document.getElementById("mySelect"); mySelect.parentNode.removeChild(mySelect);}
2、时间联动实战
demo:
时间联动的要点就是天数随月份变化,考虑闰年,口诀:四年一润,百年不润,四百年再润。 下面直接看代码吧。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body> <select id="year" name="year"> <option>年份</option> </select> <select id="month" name="month"> <option>月份</option> </select> <select id="day" name="day"> <option>日</option> </select> <script> function formatDate(){}; formatDate.prototype={ init:function(){ var _this = this; yObj = document.getElementById("year"); mObj = document.getElementById("month"); dObj = document.getElementById("day"); this.yObj = yObj; this.mObj = mObj; this.dObj = dObj; var year = new Date().getFullYear(); for(var i = year;i >= 1900;i--){ yObj.options.add(new Option(i,i)); } for(var j=1;j<=12;j++){ mObj.options.add(new Option(j,j)); } yObj.onchange = function(){ _this.day(); } mObj.onchange = function(){ _this.day(); } }, day:function(){ this.dObj.options.length = 1 var y = this.yObj.options[yObj.selectedIndex].value; var m = this.mObj.options[mObj.selectedIndex].value; var days = [31,28,31,30,31,30,31,30,30,31,30,31] if((y%4 == 0 && y%100 != 0) || y%400 == 0 ){ days[1]++; } for(var k = 1;k <= days[m-1]; k++){ this.dObj.options.add(new Option(k,k)); } } } var f = new formatDate(); f.init(); </script></body></html>
new Option()——实现时间联动
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。