我尝试了下一个和前5年的html代码下降..我接下来的5年正确...我怎么能得到前5年

时间:2015-04-01 12:05:58

标签: javascript html drop-down-menu

我尝试了下一个和前5年的html代码下拉..我接下来的5年正确...我怎么能得到前5年

请他,请将代码发给我               

function populatedropdown(yearfield){
var today=new Date()
var yearfield=document.getElementById(yearfield)
var thisyear=today.getFullYear()
for (var y=0; y<5; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}

</script>
  </head>
  <body>
<form action="" name="someform">
<select id="yeardropdown">
</select> 
</form>

<script type="text/javascript">

//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("yeardropdown")
}
</script>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

试试这个

function populatedropdown(yearfield) {
  var today = new Date(),
      yearfield = document.getElementById(yearfield),
      beforeYears = 3
      afterYears = 5,
      thisyear = today.getFullYear();
  
  for (var year = thisyear-beforeYears, index = 0; 
           index <= beforeYears + afterYears; 
           index++, year++) {
    yearfield.options[index] = new Option(year, year);
  }
  yearfield.value = thisyear;
    //select today's year
}

//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload = function() {
  populatedropdown("yeardropdown")
}
<form action="" name="someform">
  <select id="yeardropdown">
  </select>
</form>

答案 1 :(得分:0)

尝试更改for循环应该执行-5到5

for (var y=0; y<5 && y>(-5); y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}