无法显示图像,具体取决于从下拉列表中选择的项目



尝试根据用户从下拉列表中选择的内容显示图像。现在,当我选择图像1时,它只显示图像2,我不知道问题出在哪里

<HTML>
<BODY>
Chose an image:
<select id = "choice">
<option>Image 1</option>
<option>Image 2</option>
</select>
<button onclick = "showImage()">Show image</button>
<img src = " " id = "chosenImage" width = 250 height = 250>
<script>
function showImage(){
var dropDownName = document.getElementById("choice");
var imageChosen = dropDownName.options[dropDownName.selectedIndex].text;
if (imageChosen == "image 1"){
document.getElementById("chosenImage").src = "land.jpg";
}else{
document.getElementById("chosenImage").src = "code.png";
}
}
</script>
</BODY>

</HTML>

您只需向option元素添加一个value属性,然后将其用作确定要显示的内容的基础。

第一个示例:

<html>
<body>
Chose an image:
<select id = "choice">
<option value="default">Default</option>
<option value="image_1">Image 1</option>
<option value="image_2">Image 2</option>
</select>
<button onclick = "showImage()">Show image</button>
<img src="https://4197r62cmrjs32n9dndpi2o1-wpengine.netdna-ssl.com/wp-content/uploads/2020/07/square-placeholder.jpg" id="chosenImage" width='250' height ='250'>

<script>
function showImage() {
var dropDownName = document.getElementById("choice");
var imageChosen = dropDownName.options[dropDownName.selectedIndex].value;
if (imageChosen == "image_1"){
imageChosen = "https://pbs.twimg.com/profile_images/1220067947798024192/30eZhfxx_400x400.png";
} else if (imageChosen == 'image_2') {
imageChosen = 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Unofficial_JavaScript_logo_2.svg/2048px-Unofficial_JavaScript_logo_2.svg.png';
} else {
imageChosen = "https://4197r62cmrjs32n9dndpi2o1-wpengine.netdna-ssl.com/wp-content/uploads/2020/07/square-placeholder.jpg";
}
document.getElementById("chosenImage").src = imageChosen;
}
</script>
</body>
</html>

或者,您可以通过将图像的路径放置在value属性中来缩短它,如下所示。

第二个示例:

<html>
<body>
Chose an image:
<select id="choice">
<option value="https://4197r62cmrjs32n9dndpi2o1-wpengine.netdna-ssl.com/wp-content/uploads/2020/07/square-placeholder.jpg">Default</option>
<option value="https://pbs.twimg.com/profile_images/1220067947798024192/30eZhfxx_400x400.png">Image 1</option>
<option value="https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Unofficial_JavaScript_logo_2.svg/2048px-Unofficial_JavaScript_logo_2.svg.png">Image 2</option>
</select>
<button onclick="showImage()">Show image</button>
<img src="https://4197r62cmrjs32n9dndpi2o1-wpengine.netdna-ssl.com/wp-content/uploads/2020/07/square-placeholder.jpg" id="chosenImage" width='250' height='250'>
<script>
function showImage() {
var dropDownName = document.getElementById("choice");
var imageChosen = dropDownName.options[dropDownName.selectedIndex].value;
document.getElementById("chosenImage").src = imageChosen;
}
</script>
</body>
</html>

问题是

if (imageChosen == "image 1"){

应该是if (imageChosen == "Image 1"){我将大写

最新更新