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

房东的猫 提交于 2019-11-30 19:08:50

问题


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="volvo.png";
return false;
}

And so on for each car.

<img id="image" src="Null_Image.png"/>
<select id="CarList">
<option onclick="nullCar()">No Car</option>
<option onclick="volvoCar()">Volvo</option>
<option onclick="audiCar()">Audi</option></select>

I can't seem to find anything online that gives me a solution. Whether it's because I'm phrasing it awkwardly or because what I'm trying to do is impossible with javascript, I don't know.


回答1:


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




回答2:


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!



来源:https://stackoverflow.com/questions/16661565/displaying-an-image-when-selecting-an-option-from-a-drop-down-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!