所以我有这个代码来检查日期并相应地更新列表,现在我想要实现的是,当月份和年份都设置为空时“mm”“yyyy”设置为日期选择包含一个值为 null 的元素“dd”的列表。但我一直有一个错误,无法设置未定义的属性“值”。年和月中的第一个元素都设置为 null 值。
这是一个人帮我想出的 JavaScript 函数:
function monthDays (type) {
if(document.getElementById('monthof' + type).value == null || document.getElementById('yearof' + type).value == null)
{
var mod = document.getElementById('dayof' + type);
mod.length = 1;
mod[0].value = null;
mod[0].text = "DD";
}
else{
var month = parseInt(document.getElementById('monthof' + type).value, 10),
days = new Date(document.getElementById('yearof' + type).value, month + 1, 0).getDate(),
i;
var mod = document.getElementById('dayof' + type);
mod.length = days + 1;
mod[0].value = null;//this is where i am getting the error
mod[0].text = "DD";
for(i = 1; i < days+1; i++) {
mod[i].value = i;
mod[i].text = i;
}
}
}
html 出生: 毫米
<select id="dayofbirth" class="date" name="dayhofbirth">
<option value=null>DD</option>
</select>
<select id="monthofbirth" class="year" name="monthofbirth" onchange="monthDays('birth')">
<option value=null>MM</option>
</select>
<select id="yearofbirth" class="year" name="monthofbirth" onchange="monthDays('birth')">
<option value=null>YYYY</option>
</select>
</div>
类型是用来告诉函数应该编辑哪个,因为在我的 html 中我有 2 个出生日期。
最佳答案
当您选择 select
元素时,getElementById( )
返回的对象返回对元素的引用,而不是选项数组。您可以通过对象上的属性访问选项,但不需要这样做来设置所选选项。要设置所选选项,只需像您一样设置值,但删除 [0]
部分。您还需要将 null
设置为字符串 ('null'
),因为它是 HTML 中的字符串值。
这是我为您想到的:
HTML
<select id="dayofbirth" class="date" name="dayhofbirth">
<option value=null>DD</option>
<option value=01>01</option>
</select>
<select id="monthofbirth" class="year" name="monthofbirth" onchange="monthDays('birth')">
<option value=null>MM</option>
<option value=12>12</option>
</select>
<select id="yearofbirth" class="year" name="monthofbirth" onchange="monthDays('birth')">
<option value=null>YYYY</option>
<option value=1900>1900</option>
</select>
Javascript
function monthDays(type) {
if(document.getElementById('monthof' + type).value == null || document.getElementById('yearof' + type).value == null)
{
var mod = document.getElementById('dayof' + type);
mod.length = 1;
mod.value = 'null';
}
else{
var month = parseInt(document.getElementById('monthof' + type).value, 10),
days = new Date(document.getElementById('yearof' + type).value, month + 1, 0).getDate(),
i;
var mod = document.getElementById('dayof' + type);
mod.value = 'null';
for(i = 1; i < days+1; i++) {
mod.add(i);
}
}
}
在此处查看实际效果:http://jsfiddle.net/CT54h/
它可能不会做您想要的所有事情,但在它所做的问题范围内。
关于javascript - 无法在 JavaScript 中设置属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252171/