Displaying an image when selecting an option from a drop down list

前端 未结 2 1176
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 23:45

I\'m trying to change an image upon selection of an option in a drop down list:

function volvoCar()
{
var img = document.getElementById(\"image\");
img.src=\         


        
相关标签:
2条回答
  • 2021-01-07 00:18

    Instead of setting the onClick event for an option, set the onChange event for the select.

    HTML

    <img id="image" src="Null_Image.png" />
    <select id="CarList">
        <option value="Null_Image.png">No Car</option>
        <option value="volvo.png">Volvo</option>
        <option value="audi.png">Audi</option>
    </select>
    

    JavaScript

    function setCar() {
        var img = document.getElementById("image");
        img.src = this.value;
        return false;
    }
    document.getElementById("CarList").onchange = setCar;
    

    Here's a working demo

    0 讨论(0)
  • 2021-01-07 00:21

    Okay, you're doing several things wrong.

    1. Your function is called volvoCar and you are attempting to use a function called VolvoCar - JavaScript is case sensitive.

    2. This isn't the best way to assign an event-listener. You're adding it in the HTML, which is considered 'messy' (see Unobtrusive JavaScript). Also, you want to attach the function, not the result of the function (which you are doing by calling it). Functions are first-class objects in JavaScript.

    3. onclick is the wrong event handler to use in this case. You want to use the onchange handler of the <select> element.

    So:

    HTML:

    <img id="image" src="Null_Image.png"/>
    <select id="CarList">
        <option value="Null">No Car</option>
        <option value="Volvo">Volvo</option>
        <option value="Audi">Audi</option>
    </select>
    

    JS:

    var changeCarImage = function () { 
        document.getElementById('image').src = this.options[this.selectedIndex].value + "_Image.png"
    }
    
    var carList = document.getElementById('CarList');
    carList.addEventListener('change', changeCarImage, false); // Note this has some issues in old browsers (IE).
    

    This can be seen working here!

    0 讨论(0)
提交回复
热议问题