javascript 动态填充选择选项javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18158818/
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-27 10:55:21 来源:igfitidea点击:
populating select options dynamically javascript
提问by user2408578
I want to have option for select list dynamically. I want to populate select list for year values dynamically using java script. It should be current year to next 10 years as drop down, any idea?
我想有动态选择列表的选项。我想使用 java 脚本动态填充年份值的选择列表。它应该是今年到未来 10 年的下降,知道吗?
<form action="something">
some other fields
<select id="year">
</select>
</form>
回答by faino
Quick and dirty, this will do the trick:
又快又脏,这可以解决问题:
window.onload = function(){
var year = (new Date()).getFullYear(), select = document.getElementById("year"), option = null, next_year = null;
for(var i = 0; i <= 10; i++) {
option = document.createElement("option");
next_year = parseInt(year, 10) + i;
option.value = next_year;
option.innerHTML = next_year;
select.appendChild(option);
}
};
回答by jeff
Untesteded code:
未经测试的代码:
function populateYears( nbrOfYears, divID ) {
var id = document.getElementById( divID );
var dt = new Date();
var yr = dy.getFullYear();
var opt;
for( var x=0; x<= nbrOfYears; x++ ) {
opt = new Option( yr, yr );
id.appendChild( opt );
yr++;
}
}