我希望使用javascript在下拉列表中填写五年,这些年份将在今年之后.
例如:
如果当前年份是2012年那么下降值是2012,2013,2014,2015,2016
HTML
<form id="someform">
<select id="year"></select>
</form>
Run Code Online (Sandbox Code Playgroud)
JavaScript的
var myselect = document.getElementById("year"), year = new Date().getFullYear();
var gen = function(max){do{myselect.add(new Option(year++,max--),null);}while(max>0);}(5);
Run Code Online (Sandbox Code Playgroud)
一点点更好的JavaScript功能:
var myselect = document.getElementById("year"),
startYear = new Date().getFullYear()
count = 5;
(function(select, val, count) {
do {
select.add(new Option(val++, count--), null);
} while (count);
})(myselect, startYear, count);
Run Code Online (Sandbox Code Playgroud)
您可以像这样获得年份列表...
var date = new Date,
years = [],
year = date.getFullYear();
for (var i = year; i < year + 5; i++) {
years.push(i);
}
Run Code Online (Sandbox Code Playgroud)
或实际创建您的select元素...
var date = new Date,
year = date.getFullYear(),
select = document.createElement('select');
for (var i = year; i < year + 5; i++) {
var option = document.createElement('option'),
yearText = document.createTextNode(i);
option.appendChild(yearText);
select.add(option);
}
select.name = 'year';
document.body.appendChild(select);
Run Code Online (Sandbox Code Playgroud)