JavaScript:如何通过元素ID切换图片?我的代码为何失效?
问题分析与解决方案
你的代码问题出在赋值逻辑错误:你把Img_1这个DOM图片元素直接赋值给了MarioImg的src属性,但src需要的是图片的URL字符串,不是DOM对象本身。浏览器无法将一个DOM元素解析为图片地址,所以才会显示加载失败的占位图。
修正后的代码
直接取Img_1的src属性值赋值给MarioImg即可:
<img id="MarioImg" class="mariowonder" src="https://media.gamestop.com/i/gamestop/20006717?$pdp$$&fmt=webp" /> <img onclick="SwitchImg1()" id="Img_1" class="mariosideimg" src="https://media.gamestop.com/i/gamestop/20006717?$pdp$$&fmt=webp" /> <script> function SwitchImg1() { // 取Img_1的src属性值,而非元素本身 document.getElementById("MarioImg").src = document.getElementById("Img_1").src; } </script>
额外优化建议
如果希望代码更高效,可以提前缓存DOM元素,避免每次点击都重复调用getElementById查找节点:
<img id="MarioImg" class="mariowonder" src="https://media.gamestop.com/i/gamestop/20006717?$pdp$$&fmt=webp" /> <img onclick="SwitchImg1()" id="Img_1" class="mariosideimg" src="https://media.gamestop.com/i/gamestop/20006717?$pdp$$&fmt=webp" /> <script> // 提前获取并缓存元素 const marioImg = document.getElementById("MarioImg"); const targetImg = document.getElementById("Img_1"); function SwitchImg1() { marioImg.src = targetImg.src; } </script>
另外注意:你第一个img标签末尾多了个多余的分号;,虽然浏览器通常会容错,但建议去掉以保持代码规范。
内容的提问来源于stack exchange,提问作者ThatOneCoder56
相关产品推荐
相关产品推荐

