a [2]是从1到100的一个随机整数变量。当它小于33时,它变为红色,但是当它大于33时,它保持黑色。有人知道为什么它忽略了最后两个案例吗?
<script type="text/javascript">
switch (a[2]) {
case < 33:
document.getElementByID('speechstat').style.color = "red";
break;
case >= 33 && <= 66:
document.getElementByID('speechstat').style.color = "blue";
break;
case > 66:
document.getElementByID('speechstat').style.color = "green";
break;
}
</script>
答案 0 :(得分:1)
在JavaScript中,switch语句的外观与您发布的外观不同。例如,这里有一些documentation on switch
statements on MDN。
如果要检查范围,则应使用常规if/else
语句进行检查。
<script type="text/javascript">
var color;
// Check the possible value ranges.
if (a[2] < 33) { color = 'red'; }
else if (a[2] >= 33 && a[2] <= 66) { color = 'blue'; }
else if (a[2] > 66) { color = 'green'; }
document.getElementByID('speechstat').style.color = color;
</script>
答案 1 :(得分:0)
在Javascript中,您不能将变量与switch
进行比较,但是可以间接地进行比较,因为本文的答案显示:switch statement to compare values greater or less than a number
进行一些编辑并添加一些html来检查一切是否正常,这是您在这种情况下的处理方式:
<!DOCTYPE html>
<html>
<body>
<p id="speechstat1"></p>
<p id="speechstat2"></p>
<p id="speechstat3"></p>
<script type="text/javascript">
var a = 34; //You can set this to whatever you want or a user's input
switch (true) {
case (a<33):
document.getElementById("speechstat1").innerHTML = "red works";
break;
case a>= 33 && a<= 66:
document.getElementById('speechstat2').innerHTML = "blue works";
break;
case a> 66:
document.getElementById("speechstat3").innerHTML = "green works";
break;
}
</script>
</body>
</html>
.innerHTML
只是为了表明它可行,您可以替换那些
与您想实现的一切保持一致。Switch
更改为switch
.getElementByID
更改为.getElementById
拼写很重要!case >= 33 <= 66:
您
需要添加“和”运算符case >= 33 **&&** <= 66:
a[2]
更改为a
,所以它不会出错,因为它没有命名
正确总的来说,像Morgan Wilde所述的if和else语句更容易使用。