我想在Javascript中添加多个选择
当我尝试选择两个选项时,它会给我两次第一个选项 代码如下:我想在Javascript中添加多个选择,javascript,html,web,Javascript,Html,Web,当我尝试选择两个选项时,它会给我两次第一个选项 代码如下: <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 &
<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>
函数选择(){
var y=document.getElementById(“s”);
var x=document.getElementById(“输出”);
var选择=y值;
对于(i=1;i如果你改变
x.innerHTML += "the language is, " + choice + "<br>";
x.innerHTML+=“语言为“+choice+”
”;
到
x.innerHTML+=“语言为“+current.value+”
”;
它会起作用的
函数选择(){
var y=document.getElementById(“s”);
var x=document.getElementById(“输出”);
var选择=y值;
对于(i=1;i无需var choice=y.value;
),它永远无法告诉您所有的选择。正如您在打印该变量时从代码的其余部分可以看到的,它只包含第一个选择
相反,只需替换:
x.innerHTML += "the language is, " + choice + "<br>";
x.innerHTML+=“语言为“+choice+”
”;
与
x.innerHTML+=“语言为“+current.value+”
”;
您已经在检查每个选项是否被选中,因此只需输出每个选项的值即可
干杯!refere我的答案不管用吗?我写这个答案比其他答案早10分钟。这是一样的?但是,也许OP认为其他答案提供了更多的信息(尽管对他们的帖子来说有点讽刺,哈哈!),我不知道;我不能代表他们说话。没问题,你的支持票比他现在接受的更有价值。他需要阅读一些关于在这里使用的规则,以及为什么人们会花宝贵的时间来回答这样的问题。有人需要帮助,而不是有时。
x.innerHTML += "the language is, " + choice + "<br>";
x.innerHTML += "the language is, " + current.value + "<br>";