I have a select html element for years, I want it's default value to be only "年", but my js code is rewriting it. What should I do?
<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>
When you are recreating the Select options. Instead of keepin var options = "";
keep it as 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>
It's better to keep HTML in the HTML when possible…
… So, I would just append your options
using +=
instead of =
.
See it in a working snippet:
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>
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.