我希望使用javascript在下拉列表中填写五年,并且年份将在当前年份之后。
例如:
如果当前年份是2012年那么下降值是2012,2013,2014,2015,2016
答案 0 :(得分:6)
HTML
<form id="someform">
<select id="year"></select>
</form>
的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);
更好的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);
答案 1 :(得分:4)
你可以得到这样的年份清单......
var date = new Date,
years = [],
year = date.getFullYear();
for (var i = year; i < year + 5; i++) {
years.push(i);
}
或者实际创建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);
答案 2 :(得分:3)
如果您使用jQuery,则可以按照以下步骤完成任务:
var currentYear = new Date().getFullYear();
for (var i = 1; i <= 5; i++ ) {
$("#timeSelector").append(
$("<option></option>")
.attr("value", currentYear)
.text(currentYear)
);
currentYear++;
}
查看演示
答案 3 :(得分:0)
var currentYear = new Date().getFullYear();
for (var i = 0; i < 5; i++ ) {
$("#years").append(
$('<option/>')
.attr("value", currentYear + i)
.text(currentYear + i));
}