[英]How can I get different pictures being shown depending on the different options being selected in a select box?
I'm having a select box with multiple options and I'm trying to figure out a way to make a picture appear for each of the options, depending on the one that is being selected. 我有一个带有多个选项的选择框,我试图找到一种方法使每个选项都显示图片,具体取决于所选择的选项。 I'm in great need of help here as I need to make this work as soon as possible.
我非常需要帮助,因为我需要尽快进行这项工作。 I'm trying to make it happen automatically (when the option is selected) or with a button (depending on the option that is selected) but so far I couldn't come up with anything that would work.
我试图使它自动发生(当选择了选项时)或使用按钮(取决于所选择的选项),但是到目前为止我还没有提出任何可行的方法。 Any help is seriously appreciated.
任何帮助深表感谢。
Thanks in advance! 提前致谢!
You should check the value of the selected <option>
and change the <img>
src to the path of the image you want. 您应该检查所选
<option>
的值,然后将<img>
src更改为所需图像的路径。 To do that, you need to call a function when the user change the <select>
's <option>
. 为此,您需要在用户更改
<select>
的<option>
时调用一个函数。
Here is a sample: 这是一个示例:
The onchage="changeImage();
makes <select>
call the function changeImage()
every time a new <option>
is selected. onchage="changeImage();
<select>
新的<option>
时, onchage="changeImage();
可使<select>
调用函数changeImage()
。
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<select id="selectbox" onchange="changeImage();">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JavaScript</option>
</select>
<img id="img" src="" />
</body>
</html>
<script type="text/javascript">
function changeImage(){
var selectBox = document.getElementById("selectbox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
document.getElementById("img").src = selectedValue + ".png";
}
</script>
You can check the value of the selected <option>
with selectBox.options[selectBox.selectedIndex].innerHTML
too. 您也可以使用
selectBox.options[selectBox.selectedIndex].innerHTML
检查所选<option>
的值。 That will make it easier if you have a lot of options and do not want to set the value
of everything. 如果您有很多选择并且不想设置所有
value
,那么这将使操作变得更加容易。
If the images on your server have the same names as the value of each option, you don't even need to use a if statement. 如果服务器上的映像与每个选项的值具有相同的名称,则您甚至不需要使用if语句。 However, if the images are in different places or have different names/extensions, you can set the code like this:
但是,如果图像位于不同的位置或具有不同的名称/扩展名,则可以这样设置代码:
<script type="text/javascript">
function changeImage(){
var selectBox = document.getElementById("selectbox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
var img = document.getElementById("img");
if (selectedValue == "html"){
img.src = "images/html.png";
} else if (selectedValue == "css"){
img.src = "images/css.jpeg";
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.