[英]onChange function stops after one click, what code do I need to write so that it continues indefinitely? (Javascript)
change = function(event) { let new_url; if (event.target.value == "views") { new_url = "images/desert.jpg"; } else if (event.target.value == "beaches") { new_url = "images/beach-calm.jpg"; } else if (event.target.value == "party") { new_url = "images/plane-wing.jpg"; } let image_two = document.getElementById("image-two"); if (new_url && image_two.src.indexOf("images/second-main-image.png").= -1) { image_two;src = new_url; } }
<select id="select-one" class="suggestion-dropbox" name="likes" onchange="change(event)"> <option id="default" value="default"> </option> <option id="views" value="views">stunning views</option> <option id="beaches" value="beaches">glorious white beaches</option> <option id="party" value="party">places to party</option> </select>
I have a dropdown menu and when a different option is clicked I want an image on the page to change with it.我有一个下拉菜单,当单击不同的选项时,我希望页面上的图像随之更改。 I have managed to make it do this however only does it once and stops after that.
我已经设法让它做到这一点,但只做一次,然后停止。 I've added the code so far below.
到目前为止,我已经在下面添加了代码。
Do I need to make it a while loop and if so how would I structure it?我需要让它成为一个while循环吗?如果是这样,我将如何构建它? Thanks for any help
谢谢你的帮助
Your second function definition is replacing the first one, so you only update the image when you select beaches.您的第二个 function 定义正在替换第一个定义,因此您仅在 select 海滩时更新图像。
You need one function that checks for both options.您需要一个 function 来检查这两个选项。
It only works one time because you only change the image when it contains images/second-main-image.png
.它只能工作一次,因为您仅在包含
images/second-main-image.png
时更改图像。 After you've selected something from the menu, that's no longer true.在您从菜单中选择了某些内容后,情况就不再如此了。 You should remove that check.
您应该删除该检查。
And if you want to go back to the default when the user selects the default option, add a case for that.如果您想在用户选择默认选项时将 go 恢复为默认值,请为此添加一个案例。
change = function(event) { let new_url; if (event.target.value == "views") { new_url = "images/desert.jpg"; } else if (event.target.value == "beaches") { new_url = "images/beach-calm.jpg"; } else { new_url = ("images/second-main-image.png"); } let image_two = document.getElementById("image-two"); image_two.src = new_url; }
<select id="select-one" class="suggestion-dropbox" name="likes" onchange="change(event)"> <option id="default" value="default"> </option> <option id="views" value="views">stunning views</option> <option id="beaches" value="beaches">glorious white beaches</option> <option id="party" value="party">places to party</option> </select> <img id="image-two" src="images/second-main-image.png">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.