我想要做的是根据所选索引的值更改框的.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 =&#34; box&#34;的innerHTML。但我需要做的是根据selectedindex的值更改框的innerhtml。我认为问题与我的下拉菜单相互连接有关。谢谢!
答案 0 :(得分:1)
从我看到你只有一个小错误。在你的select2中,你的值中有空格,所以当你用“corvette”验证strUser时,它会返回false,因为value实际上是“corvette”。你可以做的是来自javascript的用户trim()函数。喜欢这个
var strUser = e.options[e.selectedIndex].value.trim();
这将删除所选字符串开头和结尾的空格,并且应该正确验证。