使用JS根据下拉选项更改图像

时间:2015-10-25 19:24:12

标签: javascript html

所以我已经设置了一些代码,由于某些原因,当通过下拉列表选择选择时,我无法更改图像。总共5张图片。我设置了它,但出于某种原因,我的图像似乎没有被选中。这是代码;

<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>

我的每张图片都被标记为sun0 sun1 sun2 sun3和sun4,所有这些都是jpg 我无法找到问题,而且我现在一直在查看代码。有什么建议?

3 个答案:

答案 0 :(得分:0)

switch (sun) {应为switch (sunimg) {

答案 1 :(得分:0)

在每个案例行后用冒号替换分号并使用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;

答案 2 :(得分:0)

...和

case 1:
    break;
case 2:
    break;

应该在case之后使用冒号,而不是分号!