我找到了有关如何创建用于选择年份的动态下拉列表的代码,但是我不知道如何为下拉列表添加默认值,这是我在上面找到的代码
HTML looping option values in drop down list
HTML
<select id="year"></select>
JS
var start = 2018;
var end = new Date().getFullYear();
var options = "";
for(var year = start ; year <=end; year++){
options += "<option>"+ year +"</option>";
}
document.getElementById("year").innerHTML = options;
我这样尝试过,但是不起作用
<select id="year">
<option value=''>Year</option>
</select>
还有这个
var start = 2018;
var end = new Date().getFullYear();
var options = "<option value=''>Year</option>";
for(var year = start ; year <=end; year++){
options += "<option>"+ year +"</option>";
}
document.getElementById("year").innerHTML = options;
我想要的结果是这样
<select id="year">
<option value=''>Year</option>
<option value=''>2018</option>
<option value=''>2017</option>
</select>
有人知道怎么做吗?
不会扩展会有很多答案,谢谢大家,我将尝试您的答案
答案 0 :(得分:1)
只需将selected
属性添加到option
之一中,使其成为默认的选定选项。
<select>
<option>1</option>
<option selected>2</option>
<option>3</option>
</select>
<select id="year">
</select>
<script>
var start = 2010;
var end = new Date().getFullYear();
var options = "<option value='' selected>Year</option>";
for(var year = start ; year <=end; year++){
options += "<option>"+ year +"</option>";
}
document.getElementById("year").innerHTML = options;
</script>
答案 1 :(得分:0)
尝试一下:
var start = 2015;
var end = new Date().getFullYear();
var arrDate = function(start, end) {
var count = (end - start) + 1;
return Array.apply(0, Array(count)).map(function (element, index) {
return index + start;
});
}
arrDate(start, end).forEach(function(v) {
document.getElementById("year").innerHTML += "<option value='"+v+"'>"+ v +"</option>";
});
<select id="year">
<option value=''>Year</option>
</select>
答案 2 :(得分:0)
好吧,快到了,尝试下面的代码
var start = 2012;
var end = new Date().getFullYear();
var options = "<option value='' selected>Year</option>";
for(var year = start ; year <=end; year++){
options += "<option>"+ year +"</option>";
}
document.getElementById("year").innerHTML = options;
<select id="year"></select>
答案 3 :(得分:0)
您想在年份的下拉列表中显示默认值。尝试下面的代码,让我知道您是否要这样做!
html代码:
<select id="year"></select>
js代码:
var startYear = 2017;
var endYear = new Date().getFullYear();
var options = "<option selected>"+startYear+"</option>";
for(var year = start + 1; year <= end; year++){
options += "<option>"+ year +"</option>";
}
document.getElementById("year").innerHTML = options;
答案 4 :(得分:0)
如果我正确理解了这个问题,我们想选择当前年份。
var start = 2017;
var end = new Date().getFullYear();
var options = "<option value=''>Year</option>";
for (var year = start; year <= end; year++) {
var selected = year === end ? " selected" : "";
options += "<option value=\"" + year + "\"" + selected + ">"+ year +"</option>";
}
document.getElementById("year").innerHTML = options;