在输入字段下拉列表中添加上一个hundread年份列表

时间:2017-08-20 14:03:35

标签: javascript jquery html

我想在下拉列表中添加最近几百年的年度列表。我怎样才能做到这一点。

var time = new Date();
var year = time.getYear();
if (year < 1900) {
    year = year + 1900;
}
var date = year - 101; /*change the '101' to the number of years in the past you want to show */
var future = year + 100; /*change the '100' to the number of years in the future you want to show */ 
document.writeln ("<FORM><SELECT><OPTION value=\"\">Year");
do {
    date++;
    document.write ("<OPTION value=\"" +date+"\">" +date+ "");
}
while (date < future)
document.write ("</SELECT></FORM>");

1 个答案:

答案 0 :(得分:0)

不推荐使用date.getYear(),而是使用date.getFullYear()。 一个例子:

<select id="selYears"></select>

var selectList = document.getElementById('selYears')
var d = new Date()
var year = d.getFullYear()
var past = 200 // change num here
var future = 250 // change num here
for(var i = (year - past);i <= (year + future); i++) {
       var option = document.createElement("option");
        option.value = i;
        option.text = i;
        selectList.appendChild(option);
}

修改

只需将for循环更改为从最大未来日期到最低过去日期递减:

for(var i = (year + future);i >= (year - past); i--) {
           var option = document.createElement("option");
            option.value = i;
            option.text = i;
            selectList.appendChild(option);
}