简体   繁体   English

使用JS根据下拉菜单选择更改图像

[英]Using JS to change an image depending on dropdown choice

so I have some code set up already and for some reason I can't get the image to change when a selection is picked via the dropdown list. 因此我已经设置了一些代码,由于某些原因,当通过下拉列表选择选项时,无法更改图像。 5 images in total. 总共5张图片。 I got it set up, but for some reason my images don't seem to come up when selected. 我已经设置好了,但是由于某些原因,选择时我的图像似乎没有出现。 Here's the code; 这是代码;

<script type="text/javascript">
var sunPic = 0;

function pickSun(sunimg) {
    var message = "";

    switch (sun) {
        case "0":
            sunPic = 1;
            alert("Please make a selection or go back to bed.");
            break;

        case "1";
            sunPic = 2;
            alert("I am glad you are happy.");
            break;

        case "2";
            sunPic = 3;
            alert("I am sorry you are sad.");
            break;

        case "3";
            sunPic = 4;
            alert("It's great you are feeling cool.")
            break;

        case "4";
            sunPic = 5;
            alert("I hope you get past that soon!");
            break;
    }

    document.getElementById("sunimg").src = "sun" + sunPic + ".jpg";

} <!-- end of function -->

</script>

</head>

<body>

<div id="center" style="text-align: center; margin-top: 100px;">
<img src="sun0.jpg" id="sunimg" alt="Question Sun">
<!-- start if drop down list -->
<select id="sunlist" onChange="pickSun(this.value);">
    <option value="0">Select</option>
    <option value="1">Happy</option>
    <option value="2">Sad</option>
    <option value="3">Cool</option>
    <option value="4">Unsure</option>
</select>
</div>

Each of my images is labeled as sun0 sun1 sun2 sun3 and sun4, all of them jpg I can't find the problem and I've been looking at the code for a good while now. 我的每个图像都被标记为sun0 sun1 sun2 sun3和sun4,所有这些jpg我都找不到问题,而且我已经看了好一阵子了。 Any suggestions? 有什么建议么?

switch (sun) {应该是switch (sunimg) {

Replace your semicolons with colons after each case line and use sunimg instead of sun: 在每个案例行之后用冒号替换分号,并使用sunimg代替sun:

switch (sunimg) {
    case "0":
        sunPic = 1;
        alert("Please make a selection or go back to bed.");
        break;

    case "1":
        sunPic = 2;
        alert("I am glad you are happy.");
        break;

    case "2":
        sunPic = 3;
        alert("I am sorry you are sad.");
        break;

    case "3":
        sunPic = 4;
        alert("It's great you are feeling cool.")
        break;

    case "4":
        sunPic = 5;
        alert("I hope you get past that soon!");
        break;

... and ...和

case 1:
    break;
case 2:
    break;

should use colon after the case , not semicolon! casecase应使用冒号,而不要用分号!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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