我实现了此功能,根据所选月份添加天数以选择列表 但它不起作用。
function daysInMonth() {
var year = document.getElementById(year).value;
var month = document.getElementById(month).value;
var dayscount = new Date(year,month, 0).getDate();
var select = document.getElementById(day);
for (var c = 1 ; c <= dayscount ; c++){
var option = document.createElement("option");
option.text = c ;
select.appendChild(option);
}
}
这是html:
<select name="evmonth" id = "month" onchange="daysInMonth()">
答案 0 :(得分:0)
只是评论:
您可以使用Option constructor为自己节省一些打字:
for (var c = 1 ; c <= dayscount ; c++){
select.appendChild(new Option(c));
}
它的支持范围也比document.createElement
更广泛,但您可能不关心此类旧浏览器。
此外,不要每次都创建28到31个新选项,而是考虑根据需要添加和删除最后3个选项,例如:
<script>
function update(el) {
var dayscount = el.value;
var daysSelect = el.form.days;
var daysLength = daysSelect.length;
daysSelect.length = daysLength > 28? 28 : daysLength;
while (daysSelect.length < dayscount) {
daysSelect.appendChild(new Option(daysSelect.length + 1));
}
}
</script>
<form>
<select name="monthLength" onchange="update(this);">
<option value="28">28
<option value="29">29
<option value="30">30
<option value="31">31
</select>
<select name="days">
</select>
</form>