如何保留选择默认选项

时间:2018-06-29 08:49:00

标签: javascript html select

我有一个选择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>

2 个答案:

答案 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>

希望有帮助。