You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 12:52:24