2

我正在尝试在选择下拉列表中的选项后更改图像:

function volvoCar()
{
var img = document.getElementById("image");
img.src="volvo.png";
return false;
}

每辆车依此类推。

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

我似乎无法在网上找到任何能给我解决方案的东西。我不知道是因为我措辞笨拙,还是因为我想要做的事情用 javascript 是不可能的。

4

2 回答 2

2

不要onClick为选项设置事件,而是为选择设置onChange事件。

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;

这是一个工作演示

于 2013-05-21T03:24:36.220 回答
1

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!

于 2013-05-21T03:31:29.970 回答