JavaScript switch 语句只执行默认情况 [英] JavaScript switch statement only executes the default case

查看:34
本文介绍了JavaScript switch 语句只执行默认情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JavaScript 的新手,编写了这个简短的脚本来为我的页面正文选择一种随机的背景颜色,但它只会继续执行默认情况.我不知道有什么问题.

I'm new to JavaScript and wrote this short script to choose a random background color for the body of my page, but it only keeps executing the default case. I don't know what's the problem.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script>
        function chC(){

            var cl=document.getElementById('demo');
            var colNo=Math.random()*4;
            switch (colNo){
                case 1:{
                    cl.style.background='red';
                }
                case 2:{
                    cl.style.background='yellow';
                }
                case 3:{
                    cl.style.background='pink';
                }
                default :{
                    cl.style.background='orange';
                }
            }

        }
    </script>
    <title></title>
</head>
<body id="demo">
<button type="button" onclick="chC();">change</button>


</body>
</html>

推荐答案

Math.random() * 4 不返回 1, 2code> 或 3,它返回类似

Math.random() * 4 doesn't return 1, 2 or 3, it returns things like

3.4111702758818865
3.9287009509280324
1.1707445457577705
1.5766741186380386
2.6374688586220145

你需要四舍五入,因为你不包括零,我猜你想上升,但这也会包括4,所以谁知道

You need to round that, and as you're not including zero, I guess you want to go up, but that would include 4 as well, so who knows

var colNo = Math.ceil( Math.random()*4 ); // 1-4
// or
var colNo = Math.floor( Math.random()*4 ); // 0-3

而且....你的开关/外壳有问题,你需要在满足条件时断开

And.... your switch/case is faulty, you need to break when a condition is met

switch (colNo) {
    case 1:
        cl.style.background = 'red';
        break;
    case 2:
        cl.style.background = 'yellow';
        break;
    case 3:
        cl.style.background = 'pink';
        break;
    default:
        cl.style.background = 'orange';
}

FIDDLE

这篇关于JavaScript switch 语句只执行默认情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆