我有一个选择html元素多年了,我希望它的默认值只有“年”,但是我的js代码正在重写它。我该怎么办?
<select id="f_year" name="f_year">
<option disabled selected value>年</option>
</select>
<script>
var start = 1900;
var end = new Date().getFullYear();
var options = "";
for(var year = start ; year <=end; year++){
options += "<option>"+ year + "年" + "</option>";
}
document.getElementById("f_year").innerHTML = options;
</script>
答案 0 :(得分:1)
重新创建“选择”选项时。将其保留为 var options = "";
var options = "<option disabled selected value>年</option>";
<select id="f_year" name="f_year">
</select>
<script>
var start = 1900;
var end = new Date().getFullYear();
var options = "<option disabled selected value>年</option>";
for(var year = start ; year <=end; year++){
options += "<option>"+ year + "年" + "</option>";
}
document.getElementById("f_year").innerHTML = options;
</script>
答案 1 :(得分:1)
最好在可能的情况下将HTML保留在HTML中...
…因此,我只用options
而不是+=
附加您的=
。
在有效的代码段中查看它:
var start = 1900;
var end = new Date().getFullYear();
var options = "";
for (var year = start; year <= end; year++) {
options += "<option>" + year + "年" + "</option>";
}
document.getElementById("f_year").innerHTML += options; // TAKIT: Modified only here!
<select id="f_year" name="f_year">
<option disabled selected value>年</option>
</select>
希望有帮助。