我正在尝试从选择列表中获取elemtmtbyid,并将所选值存储在变量中。并尝试针对该值(getelemtbyid)执行切换用例。但是switch在该变量上不起作用。 值已成功获取,但即使其他变量也无法使用该变量,开关也无法正常工作。
我也尝试过类型转换,但是不起作用。
<select id="from">
<option value="1">car 1</option>
<option value="2">car 2</option>
<option value="3">car 3</option>
</select>
<script>
var b = document.getElementById("from").value;
var c = Number(b); //type casting ... didnt helped in working with switch
//b var is not working with switch
switch (b) {
case '1':
{
alert("i am case 1");
case '2':
{
alert('i am case 2');
}
break;
}
default:
{
alert("i am default");
break;
}
}
</script>
switch应该针对switch变量执行相应的情况
答案 0 :(得分:1)
由于括号的放置,您的switch
结构不正确。删除这些,您的switch
应该可以工作:
<script>
var b = document.getElementById("from").value;
var c = Number(b); //type casting ... didnt helped in working with switch
switch (b) {
case '1':
alert("i am case 1");
case '2':
alert('i am case 2');
break;
default:
alert("i am default");
break;
}
</script>
或者,将case '2'
部分移出case '1'
:
<script>
var b = document.getElementById("from").value;
var c = Number(b); //type casting ... didnt helped in working with switch
switch (b) {
case '1':
{
alert("i am case 1");
}
case '2':
{
alert('i am case 2');
break;
}
default:
{
alert("i am default");
break;
}
}
</script>
答案 1 :(得分:0)
c
是一个数字-它是字符串b
的解析数字。因此,像这样检查数字c
:
case 1:
//Code
case 2:
//Code
default:
//Code
答案 2 :(得分:0)
这里不需要switch
语句。.这样可以减少代码复杂度。.
代码:
document
.getElementById('from')
.addEventListener('change', function() {
alert(`i am case ${this.value}`)
});
<select id="from">
<option value="default"> - </option>
<option value="1">car 1</option>
<option value="2">car 2</option>
<option value="3">car 3</option>
</select>
请注意,在示例中,我添加了EventTarget.addEventListener()来显示更改警报。仅用于演示代码
答案 3 :(得分:0)
您为开关ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch犯了语法错误
document.getElementById("from").addEventListener('change', function(e) {
var b = document.getElementById("from").value;
var c = Number(b); //type casting ... didnt helped in working with switch
switch (b) {
case '1':
alert("i am case 1");
break;
case '2':
alert('i am case 2');
break;
default:
alert("i am default");
break;
}
}, false);
<select id="from">
<option value="1">car 1</option>
<option value="2">car 2</option>
<option value="3">car 3</option>
</select>