简体   繁体   English

从选择值属性更改图像源

[英]Changing an image source from a select value property

I'm trying to change an image source based on the value in a drop-down menu, but for some reason the code I'm using doesn't seem to work. 我正在尝试根据下拉菜单中的值更改图像源,但是由于某些原因,我正在使用的代码似乎无法正常工作。

html html

<select id="strapOptions">
<option value="black">Black Strap</option>
<option value="white">White Strap</option>
</select>
<button type="button" onclick="chooseStrapColour()">Apply Strap</button> 

Javascript Java脚本

function chooseStrapColour() {
var black = "images/straps/oxford-black.png"
var white = "images/straps/oxford-white.png"
var colourRange = document.getElementById("strapOptions").value;
document.getElementById("oxStrap").src = colourRange;
}

If I change the src = at the end of the 5th line to either 'black' or 'white' then it does change the image source url, so I suspect it's something in the 4th line that's broken it. 如果我将第5行末尾的src =更改为'black'或'white',那么它的确会更改图片来源网址,因此我怀疑是第4行中的内容破坏了它。

After you got colourRange , its value is just "black" or "white" , you need to use that to further decide the string to put to src, not that value: 获得colourRange ,其值只是"black""white" ,您需要使用它来进一步确定要放入src的字符串,而不是该值:

function chooseStrapColour() {
   var black = "images/straps/oxford-black.png"
   var white = "images/straps/oxford-white.png"
   var colourRange = document.getElementById("strapOptions").value;
   var src = (colourRange === "white") ? white : black;
   document.getElementById("oxStrap").src = src;
}

Another option is just to append the color into the image src, like so 另一个选择是将颜色附加到图像src中,就像这样

 function chooseStrapColour() { var colourRange = document.getElementById("strapOptions").value; document.getElementById("oxStrap").src = "images/straps/oxford-"+colourRange+".png"; } 
 <select id="strapOptions"> <option value="black">Black Strap</option> <option value="white">White Strap</option> </select> <button type="button" onclick="chooseStrapColour()">Apply Strap</button> <img src='' id='oxStrap'/> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM