javascript - 选择 Javascript 和 HTML 选项时如何更改图像
问题描述
我对选择选项时如何显示图片感到困惑。例如,我从 HTML 中的选项中选择 Spring,它应该从外部源 Javascript 链接。一张图片应该出现一张春天的图片。我确实尝试过使用 if 语句,如果 value = "Spring" 那么会出现一个图像。
<html>
<body>
<img src="" name="changepic">
<select name="allseasons" id="allseasons">
<option value="Spring">Spring</option>
<option value="Summer">Summer</option>
<option value="Fall">Fall</option>
<option value="Winter">Winter</option>
</select>
</body>
</html>
Javascript
element=document.getElementById('allseasons');
if (value =="spring");
element.src="spring.jpg"
if (value =="summer");
element.src="summer.jpg"
if (value =="fall");
element.src="fall.jpg"
if (value =="winter");
element.src="winter.jpg"
}
解决方案
- 您应该将事件侦听器附加到
<select>
- 其次,您应该将 存储
src
在value
of 中,<option>
这样您就不需要检查每个src
. - 不要放在语句
;
的末尾。if
无论条件是真还是假,它都会始终运行它下面的代码const element = document.querySelector('#changepic'); console.log(element); document.querySelector('#allseasons').addEventListener('change',(e) => { element.src = e.target.value; console.log(element); })
<img src="" name="changepic" id="changepic"> <select name="allseasons" id="allseasons"> <option value="spring">Spring</option> <option value="summer">Summer</option> <option value="fall">Fall</option> <option value="winter">Winter</option> </select>
推荐阅读
- apache-flink - 在 Flink 运算符中读取外部文件(如图像)的最佳解决方案是什么?
- java - Junit5测试无法注入依赖但正常运行的应用程序可以注入它
- azure - Azure Pipelines:比较两个日期之间的测试结果
- function - C++ 中的套接字编程问题
- python - Vigenere Cipher 用于带有空格的句子
- sql - 连接后从两个差异表中过滤列
- angular - 在构建操作中使用 Github Actions 机密是否安全
- .net - 用于 JSON 自动的 SQKATA
- reactjs - 如何使用不同的支付选项在 React 中实施 PayPal?
- python-3.x - 拒绝主 -> 主(预接收挂钩被拒绝)