简体   繁体   中英

Why doesn't my switch statement work?

Somehow I figure the "this" keyword isn't paying reference to the value. However as you know I could use continual if/else if statements and it will work just fine. For example I could write the code this way.

if(painStatus == 1) {
    msg.innerHTML = "pain message 1";
}
else if(painStatus == 2) {
    msg.innerHTML = "pain message 2";
}

so on and so forth, but using a switch statement it fails on me. I'm sure it is something simple I am not doing right. Sorry for being a noob.

<head>

    <script type="text/javascript">
    function painLevel(val) {
            var painStatus = document.getElementById("pain_status").innerHTML = val;
            var msg = document.getElementById("painMsg");

            switch (painStatus) {
                case 1:
                    msg.innerHTML = "Pain message 1";
                    break;
                case 2:
                    msg.innerHTML = "Pain message 2";
                    break;
                    .
                    .
                    .
                default:
                    msg.innerHTML = "";

            }
        }

    </script>
</head>
<body>

<p>Please use the bar to select pain level</p>
<p>My Pain Level</p>

    <input type = "range" min="0" max="10" value="1" onchange="painLevel(this.value)" />

        Pain Level = <span id="pain_status">1</span>
        <br /><br />

        <div id="painMsg"> rePain message 1</div>
</body>

I believe you just need to parseInt like this

switch (parseInt(painStatus)) {
// As before....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM