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

如何实现条件判断:仅当指定父类含对应子类时修改兄弟父类子类文本颜色

原代码问题点

  • 脚本在head中执行时DOM尚未渲染,元素选择器无法匹配到body内的节点
  • 类选择器缺少.前缀,匹配带hide类的元素应为.hide而非hide
  • jQuery选择器无论是否匹配到元素都会返回jQuery对象(始终为真值),判断元素是否存在需要校验返回对象的length属性是否大于0
  • 不能直接在JS中书写CSS规则修改样式,需要使用jQuery提供的.css()方法操作元素样式
  • 同一页面内id不可重复,示例中两个h3共用price-fieldid属于非法结构,会导致选择器仅匹配到第一个对应节点,建议改为类标识

通用需求实现

对应你提出的「仅当parentclass1下存在childclass1子元素时修改childclass2颜色」的需求,实现代码如下:

// 等待DOM完全加载后执行逻辑
$(function() {
  if ($('.parentclass1 .childclass1').length > 0) {
    $('.parentclass2 .childclass2').css('color', 'red');
  }
});

测试代码修正版

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h5 class="compare-at-price js" style="font-size: 14px;">
    <span class="money" style="font-size: 14px;">$60</span>
</h5>
<!-- 重复id改为类标识 -->
<h3 class="custom-font price-field" style="font-size: 24px;">
    <span class="money" style="font-size: 24px;">$50</span>
</h3>
<h5 class="compare-at-price js hide" style="font-size: 14px;">
</h5>
<h3 class="custom-font price-field" style="font-size: 24px;">
    <span class="money" style="font-size: 24px;">$70</span>
</h3>

<script>
$(function() {
  // 判断是否存在带hide类的h5元素
  if ($('h5.hide').length > 0) {
    $('.price-field .money').css('color', 'red');
  }
})
</script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:45:01