我要做的是根据所选索引的值更改框的.innerHTML:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="test.js"></script>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<form>
<select id="slct1" name="slct1" onChange="populate(this.id, 'slct2')">
<option val=""></option>
<option val="Chevy">Chevy</option>
<option val="Dodge">Dodge</option>
<option val="Ford">Ford</option>
</select>
</form>
<hr />
<form>
<select id="slct2" name="slct2" onchange=handleSelect(this.form);></select>
</form>
<div id="box"></div>
</body>
</html>
这是Javascript:
function populate(s1, s2) {
var s1=document.getElementById(s1);
var s2=document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Chevy") {
var optionArray = ["|", "camaro | Camaro", "corvette | Corvette", "impala | Impala"];
}
else if (s1.value == "Dodge") {
var optionArray = ["|", "avenger | Avenger", "challenger | Challenger", "ram | Ram"];
}
else if (s1.value == "Ford") {
var optionArray = ["|", "f150 | F150", "taurus | Taurus", "mustang | Mustang"];
}
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);
}
};
var handleSelect = function (flight1) {
var e = document.getElementById("slct2");
var strUser = e.options[e.selectedIndex].value;
if (strUser == "") {
document.getElementById("box").innerHTML = "";
}
else if (strUser == "camaro") {
document.getElementById("box").innerHTML = "Good";
}
else if (strUser == "corvette") {
document.getElementById("box").innerHTML = "Better";
}
else if (strUser == "impala") {
document.getElementById("box").innerHTML = "Great";
}
if (strUser == "") {
document.getElementById("box").innerHTML = "";
}
else if (strUser == "avenger") {
document.getElementById("box").innerHTML = "Good";
}
else if (strUser == "challenger") {
document.getElementById("box").innerHTML = "Better";
}
else if (strUser == "ram") {
document.getElementById("box").innerHTML = "Great";
}
if (strUser == "") {
document.getElementById("box").innerHTML = "";
}
else if (strUser == "f150") {
document.getElementById("box").innerHTML = "Good";
}
else if (strUser == "taurus") {
document.getElementById("box").innerHTML = "Better";
}
else if (strUser == "mustang") {
document.getElementById("box").innerHTML = "Great";
}
};
我可以更改id =“ box”的innerHTML,但是我需要做的是根据selectedindex的值更改box的innerhtml。我认为问题与我的下拉菜单相互连接这一事实有关。谢谢!
最佳答案
从我看来,您只有一个小错误。在select2中,您的值中包含空格,因此,例如,当您根据“ corvette”验证strUser时,它返回false,因为value实际上是“ corvette”。您可以做的是来自javascript的用户trim()函数。像这样
var strUser = e.options[e.selectedIndex].value.trim();
这将从所选字符串的开头和结尾删除空格,并且应该正确验证。