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

扫描页面检测标题标签跳级缺失的技术实现咨询

标题标签跳级检测实现说明

该需求完全可以优先使用JavaScript或Java实现,两者适配不同的业务场景:

JavaScript适用场景与实现

适合前端实时检测的场景,比如用户在富文本编辑器自定义创作内容时实时校验,或者页面渲染完成后在客户端做运行时合规检查。
核心逻辑是按文档流顺序提取所有h1~h6标签的级别,遍历判断相邻标题的级差是否大于1,示例代码如下:

function checkHeadingSkip() {
  // 按文档流顺序获取页面所有标题元素
  const headings = Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6'));
  const skipErrors = [];
  let prevLevel = 0;

  headings.forEach((heading, index) => {
    const currLevel = Number(heading.tagName.charAt(1));
    if (index === 0) {
      prevLevel = currLevel;
      return;
    }
    // 级差超过1即为跳级
    if (currLevel - prevLevel > 1) {
      skipErrors.push(`第${index + 1}个标题存在跳级:上一级为h${prevLevel},当前为h${currLevel}`);
    }
    prevLevel = currLevel;
  });
  return skipErrors;
}

Java适用场景与实现

适合服务端离线检测的场景,比如用户提交自定义内容后在服务端做入库前校验,或者对存量站点页面做批量无障碍合规扫描。
可借助Jsoup解析HTML内容提取标题列表,复用和前端一致的校验逻辑即可,示例代码如下:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class AccessibilityChecker {
    public static void checkHeadingLevel(String htmlContent) {
        Document doc = Jsoup.parse(htmlContent);
        Elements headings = doc.select("h1, h2, h3, h4, h5, h6");
        int prevLevel = 0;
        for (int i = 0; i < headings.size(); i++) {
            int currLevel = Integer.parseInt(headings.get(i).tagName().substring(1));
            if (i == 0) {
                prevLevel = currLevel;
                continue;
            }
            if (currLevel - prevLevel > 1) {
                System.out.printf("第%d个标题存在跳级:上一级为h%d,当前为h%d%n", i + 1, prevLevel, currLevel);
            }
            prevLevel = currLevel;
        }
    }
}

你可以根据业务需求选择优先实现的端:如果需要在用户创作阶段给出实时错误提示,优先选择JavaScript实现;如果需要做服务端统一合规兜底,优先选择Java实现。

内容的提问来源于stack exchange,提问作者Vijay Narayanan S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:27:00