问题
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.
Your function is called
volvoCarand you are attempting to use a function calledVolvoCar- JavaScript is case sensitive.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.onclickis the wrong event handler to use in this case. You want to use theonchangehandler 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