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

修复jQuery代码:仅向无tb2-day子类的表格单元格添加内容

问题修复:为无日期的活动单元格添加'Ongoing Program'

我有一个活动表格,部分活动为持续进行状态,部分有特定日期。有日期的活动会显示对应日期,我需要在原本用于显示日期的空单元格中添加文本'Ongoing Program'。

我编写的代码片段旨在查找类为tb2-day的元素,仅向没有该子类的单元格添加指定文本,但目前代码会将文本添加到所有单元格中。请问该如何修复?


原代码片段

JavaScript

jQuery(document).ready(function() {
  jQuery(".product-type-simple").each(function() {
    if ($(this).find('.tb2-day').length) {
      jQuery('<p>Ongoing<br>Program</p>').appendTo('.we-first-row');
    }
  });
});

CSS

td {
  border: 1px solid #ccc;
  padding: 10px;
}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="we-table">
  <tbody>
    <tr class="product-type-simple">
      <td class="we-first-row"></td>
      <td>content</td>
      <td class="tb-viewdetails">
        <a class="btn" href="#">info</a>
      </td>
    </tr>
    <tr class="product-type-simple">
      <td class="we-first-row"></td>
      <td>content</td>
      <td class="tb-viewdetails">
        <a class="btn" href="#">info</a>
      </td>
    </tr>
    <tr class="product-type-simple">
      <td class="we-first-row">
        <span class="tb2-day">07</span>
        <span class="tb2-month">June</span>
      </td>
      <td>content</td>
      <td class="tb-viewdetails">
        <span>
          <a class="btn" href="#">info</a>
        </span>
      </td>
    </tr>
  </tbody>
</table>

错误原因

  1. 逻辑判断颠倒:原代码判断当前行存在tb2-day元素时添加文本,但实际需要的是不存在该元素时添加。
  2. 目标选择器范围过大:appendTo('.we-first-row')会选中页面所有带该类的单元格,而非当前行下的对应单元格,导致文本被批量添加到所有符合条件的单元格。

修复后的代码

JavaScript

jQuery(document).ready(function() {
  jQuery(".product-type-simple").each(function() {
    const $row = jQuery(this);
    if (!$row.find('.tb2-day').length) {
      jQuery('<p>Ongoing<br>Program</p>').appendTo($row.find('.we-first-row'));
    }
  });
});

修复说明

  • 修正判断逻辑:用!$row.find('.tb2-day').length判断当前行无日期元素时执行添加操作。
  • 缩小目标范围:通过$row.find('.we-first-row')定位到当前行内的日期单元格,确保文本仅添加到对应行的空单元格。
  • 缓存$row对象,减少重复DOM查询,提升代码性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:30:51