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

如何统计HTML表格中带active类的单元格并触发自动打开的模态框?

解决方案

1. 优化现有单元格分类逻辑

先简化你原有的脚本,正则直接使用字面量更简洁,同时增加trim()避免空白字符干扰匹配:

$('td').each(function() {
  const cellText = $(this).text().trim();
  if (/^[0-9][A-Z]/.test(cellText)) {
    $(this).addClass('active');
  } else if (/^c[0-9]/.test(cellText)) {
    $(this).addClass('none');
  }
});

2. 统计.active单元格数量

分类完成后,直接通过jQuery选择器获取目标元素并读取长度:

const activeCellCount = $('td.active').length;

3. 用模态框展示统计结果(基于jQuery UI Dialog)

你提到的autoOpen: true是jQuery UI Dialog的标准配置项,按以下步骤实现:

先在HTML中添加模态框容器

<div id="activeCountModal" title="Active单元格统计">
  <p>符合条件的单元格数量:<span id="countDisplay"></span></p>
</div>

整合逻辑到DOM就绪事件

确保页面元素加载完成后再执行所有操作:

$(document).ready(function() {
  // 为单元格添加对应class
  $('td').each(function() {
    const cellText = $(this).text().trim();
    if (/^[0-9][A-Z]/.test(cellText)) {
      $(this).addClass('active');
    } else if (/^c[0-9]/.test(cellText)) {
      $(this).addClass('none');
    }
  });

  // 统计active单元格数量
  const activeCellCount = $('td.active').length;

  // 初始化并自动打开模态框
  $('#activeCountModal').dialog({
    autoOpen: true,
    modal: true,
    width: 320
  });

  // 插入统计数值到模态框
  $('#countDisplay').text(activeCellCount);
});

注意事项

  • 确保页面已引入jQuery和jQuery UI的依赖资源:
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    
  • 若不想依赖jQuery UI,也可以自定义模态框:创建一个固定定位的div容器,默认设置display: block,把统计数值插入其中即可,核心统计逻辑保持不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:34:51