1、基礎準備: 先來瞭解下,如何運用js實現select動態添加option。 //1.動態創建select function createSelect(){ var mySelect = document.createElement("select"); mySelect.id = "mySele ...
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、時間聯動實戰
時間聯動的要點就是天數隨月份變化,考慮閏年,口訣:四年一閏,百年不閏,四百年再閏。
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>