【发布时间】:2019-07-09 14:15:48
【问题描述】:
我有一个下拉菜单,它会根据第一个选择触发一组不同的菜单。然后根据下一个选择,我想显示一个包含信息的 div。如果第二个选择发生变化,我想隐藏显示的内容并显示新选择的新内容。我遇到的问题是当做出新选择时,旧内容并没有隐藏,而新内容只是添加到它上面。
我不懂 jquery,所以我使用的是 javascript,我尝试使用 .classlist.remove 和 .add 根据 div ID 更改类名。我还尝试创建循环来检查类名是否存在并将其更改为不同的类名。
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Auto") {
var optionArray = ["|Please Select The Insurance Company", "nationwideauto|Nationwide", "progressiveauto|Progressive", "safeco|Safeco"];
} else if (s1.value == "Home") {
var optionArray = ["|Please Select The Insurance Company", "cabrillo|Cabrillo", "gulfstream|Gulfstream", "capitalpreferred|Capital Preferred"];
} else if (s1.value == "Commercial") {
var optionArray = ["|Please Select The Insurance Company", "bankers|Bankers", "travelers|Travelers", "progressive|Progressive"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
function toggle() {
var element = document.getElementById('slct2').value;
document.getElementById(element).classList.remove('inv');
document.getElementById(element).classList.add('vis');
}
.inv {
display: none;
}
.vis {
display: block;
}
<select id="slct1" name="slct1" onchange="populate(this.id, 'slct2')">
<option value "">Please Select The Type of Claim</option>
<option value="Auto">Auto Insurance Claim</option>
<option value="Home">Property Insurance Claim</option>
<option value="Commercial">Commercial Insurance Claim</option>
</select>
<select id="slct2" name="slct2" onchange="toggle(this.id)"></select>
<div id="nationwideauto" class="inv">Content 1</div>
<div id="progressiveauto" class="inv">Content 2</div>
<div id="safeco" class="inv">Content 3</div>
我只创建了前几个 div 来测试代码,预期结果是当您在第一个下拉列表中选择“自动”时,汽车保险公司会在第二个下拉列表中显示(有效)。然后,当您从第二个下拉列表中选择一家公司时,它会在 div 中显示内容(有效)。我遇到的问题是,当在下拉列表 2 中进行新选择时,我无法弄清楚如何用原始内容隐藏 div 并用新内容显示 div。我的函数 toggle() 是问题所在,我已经连续阅读和搜索了三天,但找不到有效的解决方案。
【问题讨论】:
-
使用classList.toggle,而不是添加和删除。
-
我已经尝试过了,如果第二次进行相同的选择,它只会打开和关闭它
标签: javascript html css onchange