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

根据另一div内容控制div显示/隐藏的JS实现求助

问题分析与解决方案

你的代码存在几个关键问题,导致无法实现每组独立控制的需求:

  • getElementsByClassName返回的是HTMLCollection集合,不是单个DOM元素,直接访问price.textContent或priceTag.style会无效
  • 条件判断里用了赋值运算符=而非比较运算符===,逻辑完全错误
  • 没有将每组的price和priceTag关联起来,无法实现独立控制

修正后的实现代码

HTML(先修正转义字符)

<div class="priceParent">
  <div class="priceTag">$</div>
  <div class="price">Free</div>
</div>

<div class="priceParent">
  <div class="priceTag">$</div>
  <div class="price">60</div>
</div>

JavaScript

// 获取所有父容器,遍历每一组
const parentContainers = document.querySelectorAll('.priceParent');
parentContainers.forEach(container => {
  // 在当前父容器内找对应的price和priceTag元素
  const priceEl = container.querySelector('.price');
  const priceTagEl = container.querySelector('.priceTag');
  
  // 处理文本内容(先去除首尾空白,避免空格干扰)
  const priceText = priceEl.textContent.trim();
  
  // 控制显示隐藏
  if (priceText === 'Free') {
    priceTagEl.style.display = 'none';
  } else if (!isNaN(Number(priceText))) {
    // 验证内容是否为数字
    priceTagEl.style.display = 'block';
  }
});

核心改进点

  • 使用document.querySelectorAll获取所有父容器,通过forEach遍历实现每组独立处理
  • 在每个父容器范围内用querySelector查找子元素,确保每组的元素一一对应
  • 用trim()去除文本首尾空白,避免空格导致的判断错误
  • 增加isNaN(Number(priceText))验证内容是否为数字,逻辑更严谨

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:45:54