我的页面上有这个问题,这是.. 我希望每当用户从这个选择列表中选择一个不同的选项时,就会改变选择下拉列表的选项,我使用" onchange"物业,它只是第一次运作良好!但不是每次改变选择!这是我的代码,
var SlctYear = document.getElementById("SlctYear"),
SlctMonth = document.getElementById("SlctMonth"),
SlctDay = document.getElementById("SlctDay"),
x,
option1,
option2,
option3;
for (x = 2017; x >= 1960; x -= 1) {
option1 = document.createElement("option");
SlctYear.appendChild(option1);
option1.textContent = x;
option1.setAttribute("value", "Val" + x);
}
for (x = 1; x <= 12; x += 1) {
option2 = document.createElement("option");
SlctMonth.appendChild(option2);
option2.textContent = x;
option2.setAttribute("value", "Val" + x);
}
SlctMonth.onchange = function() {
"use strict";
if (SlctMonth.options[0].selected || SlctMonth.options[2].selected || SlctMonth.options[4].selected || SlctMonth.options[6].selected || SlctMonth.options[7].selected || SlctMonth.options[9].selected || SlctMonth.options[11].selected === true) {
for (x = 31; x >= 1; x -= 1) {
option3 = document.createElement("option");
SlctDay.appendChild(option3);
option3.textContent = x;
}
} else if (SlctMonth.options[1].selected === true) {
for (x = 28; x >= 1; x -= 1) {
option3 = document.createElement("option");
SlctDay.appendChild(option3);
option3.textContent = x;
}
} else if (SlctMonth.options[3].selected || SlctMonth.options[5].selected || SlctMonth.options[8].selected || SlctMonth.options[10].selected) {
for (x = 30; x >= 1; x -= 1) {
option3 = document.createElement("option");
SlctDay.appendChild(option3);
option3.textContent = x;
}
}
};
&#13;
<label>Year</label>
<select id="SlctYear"></select>
<br>
<label>Month</label>
<select id="SlctMonth"></select>
<br>
<label>Day</label>
<select id="SlctDay"></select>
&#13;
答案 0 :(得分:2)
问题是你在添加新选项之前没有清除选项,只需在你的函数中添加循环,如下所示:
SlctMonth.onchange = function() {
"use strict";
//ADD THIS-------------------------
while (SlctDay.hasChildNodes()) {
SlctDay.removeChild(SlctDay.lastChild);
}
//--------------------------------
if (SlctMonth.options[0].selected || SlctMonth.options[2].selected || SlctMonth.options[4].selected || SlctMonth.options[6].selected || SlctMonth.options[7].selected || SlctMonth.options[9].selected || SlctMonth.options[11].selected === true) {
for (x = 31; x >= 1; x -= 1) {
option3 = document.createElement("option");
SlctDay.appendChild(option3);
option3.textContent = x;
}
} else if (SlctMonth.options[1].selected === true) {
for (x = 28; x >= 1; x -= 1) {
option3 = document.createElement("option");
SlctDay.appendChild(option3);
option3.textContent = x;
}
} else if (SlctMonth.options[3].selected || SlctMonth.options[5].selected || SlctMonth.options[8].selected || SlctMonth.options[10].selected) {
for (x = 30; x >= 1; x -= 1) {
option3 = document.createElement("option");
SlctDay.appendChild(option3);
option3.textContent = x;
}
}
};