当我尝试选择两个选项时,它会给我第一个选项两次。
以下是代码:
<head>
<script type="text/javascript">
function choices() {
var y = document.getElementById("s");
var x = document.getElementById("output");
var choice = y.value;
for (i = 1; i <= 3; i++) {
var current = y[i];
if (current.selected == true) {
x.innerHTML += "the language is, " + choice + "<br>";
}
}
}
</script>
</head>
<body>
<form action="">
<fieldset>
<select id="s" multiple="multiple" size="4">
<option>--Choose language--</option>
<option value="HTML">HTML</option>
<option value="JAVA">JAVA</option>
<option value="PHP">PHP</option>
</select>
<input type="button" value="show" onclick="choices()">
</fieldset>
</form>
<div id="output"></div>
</body>
答案 0 :(得分:4)
如果你改变了
x.innerHTML += "the language is, " + choice + "<br>";
到
x.innerHTML += "the language is, " + current.value + "<br>";
它会起作用。
function choices() {
var y = document.getElementById("s");
var x = document.getElementById("output");
var choice = y.value;
for (i = 1; i <= 3; i++) {
var current = y[i];
if (current.selected == true) {
x.innerHTML += "the language is, " + current.value + "<br>";
}
}
}
<form action="">
<fieldset>
<select id="s" multiple="multiple" size="4">
<option>--Choose language--</option>
<option value="HTML">HTML</option>
<option value="JAVA">JAVA</option>
<option value="PHP">PHP</option>
</select>
<input type="button" value="show" onclick="choices()">
</fieldset>
</form>
<div id="output"></div>
答案 1 :(得分:1)
不需要var choice = y.value;
......它永远无法告诉你所有的选择。正如您在打印该变量时从其余代码中看到的那样,它只包含第一个选择。
而只是替换:
x.innerHTML += "the language is, " + choice + "<br>";
与
x.innerHTML += "the language is, " + current.value + "<br>";
您已经在检查每个选项是否被选中,因此只需输出每个选项的值。
干杯!