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

如何让logo切换函数独立作用于所有.anonce类元素?

问题解决:让Logo切换函数作用于所有招聘信息项

原代码仅对第一个.anonce元素生效,核心问题是使用了document.querySelector()(仅返回第一个匹配元素),需修改为遍历所有.anonce元素,单独处理每个招聘项的文本与对应Logo。

修改思路

  • 用document.querySelectorAll(".anonce")获取所有招聘信息容器
  • 遍历每个容器,分别提取内部的.anonceText文本和.anonceLogo图片元素
  • 用对象映射替代重复的if判断,简化公司名到Logo路径的匹配逻辑
  • 仅检查文本的前50个字符,贴合需求

优化后的代码

JavaScript部分

function logo_switch() {
  // 获取所有.anonce招聘容器
  const anonceItems = document.querySelectorAll(".anonce");
  
  // 公司名与Logo路径的映射表,后续新增公司只需在此添加
  const logoMap = {
    'A': 'img/a.png',
    'B': 'img/b.jpg',
    'C': 'img/c.jpg',
    'D': 'img/d.jpg',
    'E': 'img/e.jpg',
    'F': 'img/f.png',
    'G': 'img/g.png'
  };

  // 逐个处理每个招聘项
  anonceItems.forEach(item => {
    // 获取当前项的文本内容,截取前50个字符并去除首尾空格
    const text = item.querySelector(".anonceText").textContent.trim().slice(0, 50);
    // 获取当前项对应的Logo图片元素
    const logoImg = item.querySelector(".anonceLogo");

    // 遍历映射表,匹配对应公司的Logo
    for (const [company, logoPath] of Object.entries(logoMap)) {
      if (text.includes(company)) {
        logoImg.setAttribute("src", logoPath);
        break; // 找到匹配项后停止遍历,避免重复覆盖
      }
    }
  });
}

HTML部分(保持原结构无需修改)

<body onload="logo_switch()">
  <div class="anonce">
    <h2>Job 1</h2>
    <div class="anonceBody">
      <img class="anonceLogo">
      <p class="anonceText">
        A
      </p>
    </div>
  </div>
  <div class="anonce">
    <h2>Job 2</h2>
    <div class="anonceBody">
      <img class="anonceLogo">
      <p class="anonceText">
        B
      </p>
    </div>
  </div>
  <div class="anonce">
    <h2>Job 3</h2>
    <div class="anonceBody">
      <img class="anonceLogo">
      <p class="anonceText">
        C
      </p>
    </div>
  </div>
  <div class="anonce">
    <h2>Job 4</h2>
    <div class="anonceBody">
      <img class="anonceLogo">
      <p class="anonceText">
        D
      </p>
    </div>
  </div>
</body>

关键改进点

  1. 全局遍历处理:通过querySelectorAll获取所有招聘容器,确保每个项都被处理
  2. 局部元素关联:在单个.anonce容器内查找子元素,保证文本与Logo的一一对应
  3. 逻辑简化维护:用对象映射替代冗余if判断,新增公司只需修改映射表
  4. 精准文本判断:直接截取前50个字符,排除多余内容干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:35:29