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

点击事件触发时无法修改event.target对应图片src,如何实现指定图片src切换效果?

问题原因及修复方案

存在的错误点

    1. 条件判断误用赋值运算符:if判断中使用了=赋值符而非==/===比较符,会直接修改src值且条件永远为真,导致第一个分支把src改成hm_2_cart_2_a.png后,第二个分支立即又改回原图,看起来没有变化。
    1. src匹配路径错误:DOM元素的src属性直接读取返回的是绝对路径(比如http://localhost:8080/static/images/hm_2_cart_2.png),和代码中写的相对路径无法匹配,应该用getAttribute('src')获取标签内写的原始相对路径,或者判断路径后缀。
    1. 多分支逻辑错误:两个if是独立判断,第一个分支修改src后会命中第二个分支的判断,造成修改被覆盖,应该用else if关联分支,或者直接用三元表达式简化逻辑。
    1. 变量获取逻辑缺失:原代码直接使用category_list_field变量,没有先通过选择器获取DOM元素,会触发变量未定义报错。

修正后的代码

// 先获取所有.category_list_field元素
const categoryfields = document.querySelectorAll('.category_list_field');

Array.from(categoryfields).forEach(field => {
  field.addEventListener('click', event => {
    const target = event.target;
    if(target.matches('.favorite_img2')) {
      // 获取标签上写的原始src属性值
      const rawSrc = target.getAttribute('src');
      // 路径切换逻辑
      if(rawSrc === './static/images/hm_2_cart_2.png') {
        target.setAttribute('src', './static/images/hm_2_cart_2_a.png');
      } else if(rawSrc === './static/images/hm_2_cart_2_a.png') {
        target.setAttribute('src', './static/images/hm_2_cart_2.png');
      }
      // 更简洁的三元写法可替换上面的分支判断:
      // target.setAttribute('src', rawSrc.includes('_a.png') 
      //   ? './static/images/hm_2_cart_2.png' 
      //   : './static/images/hm_2_cart_2_a.png'
      // )
    }
  })
})

内容的提问来源于stack exchange,提问作者h20002000

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:24:03