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

动态设置图片src属性问题求助:按性别切换图片路径

问题修复:根据选中性别动态切换图片

问题根源

你代码里的循环会遍历所有<option>元素,不管用户实际选中的是哪个选项,循环都会先执行Mr分支设置female图片,接着执行Ms分支覆盖成male图片,所以最后总是显示male文件夹的图片。

修复后的代码

修正后的JavaScript代码

document.querySelector("button").addEventListener("click", (event)=>{
  // 生成1到11之间的随机整数
  let randomNumber = Math.floor(Math.random() * 11) + 1;
  // 直接获取select的选中值,无需遍历所有option
  let selectedSex = document.querySelector(".gender").value;

  if(selectedSex === "Mr"){
    // 修正拼写错误:attress → actress
    document.querySelector(".soulmate").setAttribute("src", `images/female/actress${randomNumber}.PNG`);
  }else if(selectedSex === "Ms"){
    document.querySelector(".soulmate").setAttribute("src", `images/male/actor${randomNumber}.PNG`);
  }else{
    console.log("error"); 
  }
})

关键优化点

  • 直接通过select元素的value属性获取用户选中的性别,避免遍历option导致的覆盖问题
  • 简化随机数生成逻辑,合并为一行代码更简洁
  • 修正路径里的拼写错误attress为actress,防止图片加载失败
  • 用模板字符串拼接路径,可读性更强

注意事项

确保页面中存在class为soulmate的<img>标签,否则JS无法找到该元素设置src属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:06:21