我想使用 javascript 在下拉列表中填充五年,并且年份将在当前年份之后

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6274417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:07:38  来源:igfitidea点击:

I want fill five years in a drop-down using javascript and the years will be after the current years

javascript

提问by Sanjeev

I want fill five years in a drop-down using javascript and the years will be after the current year.

我想使用 javascript 在下拉列表中填充五年,并且年份将在当前年份之后。

for example:

例如:

if current year is 2012 then the drop-down values are 2012,2013,2014,2015,2016

如果当前年份是 2012 则下拉值是 2012,2013,2014,2015,2016

采纳答案by Bakudan

HTML

HTML

<form id="someform">
<select id="year"></select>
</form>

JavaScript

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);

A little bit better JavaScript function:

稍微好一点的 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);

jsFiddle, new jsFiddle

jsFiddle,新的 jsFiddle

回答by alex

You could get the list of years like so...

你可以得到这样的年份列表......

var date = new Date,
    years = [],
    year = date.getFullYear();

for (var i = year; i < year + 5; i++) {
   years.push(i);   
}

jsFiddle.

js小提琴

Or to actually create your selectelement...

或者实际创建您的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);

jsFiddle.

js小提琴

回答by Genzer

If you use jQuery, the task can be achieved as follow:

如果您使用 jQuery,则可以按如下方式完成任务:

   var currentYear = new Date().getFullYear();  

    for (var i = 1; i <= 5; i++ ) {
        $("#timeSelector").append(

            $("<option></option>")
                .attr("value", currentYear)
                .text(currentYear)

        );
        currentYear++;
    }

View demo at jsFiddle

jsFiddle查看演示

回答by electricalbah

var currentYear = new Date().getFullYear(); 
     for (var i = 0; i < 5; i++ ) {
            $("#years").append(
               $('<option/>')
               .attr("value", currentYear + i)
               .text(currentYear + i));
        }