章节标题、目录中的计数器增加

章节标题、目录中的计数器增加

我正在尝试为小节标题添加计数器。例如:

  1. 设计测试

    1.1 测试 1. 测试

    1.2 测试2. 另一项测试

  2. 功能测试

    2.1 测试 3. 另一个测试

问题是,由于目录中的计数器也增加了,目录将显示:

1.1 测试 1. 测试 A(另外两个测试是 2 和 3)

但文档中的部分内容将是:

1.1 测试4. 测试A(另外两个测试将是5和6)

我怎样才能使用计数器跳过目录?

以下是示例代码:

\documentclass{article}

\newcounter{test}
\DeclareRobustCommand{\newtest}[1]{
\refstepcounter{test} \label{test:#1} 
Test \thetest #1
}

\begin{document}
   \title{Test example}

   \maketitle

   \clearpage

   \tableofcontents

   \clearpage

    \section{Design tests}
      \subsection{\newtest{A test}}
      \subsection{\newtest{Another test}}
    \section{Functional tests}
      \subsection{\newtest{Yet another test}}
\end{document}

答案1

这种方法通过使用名为的条件在 的开头将 设置为 false 来阻止\refstepcounter代码在 中未执行的情况。\tableofcontents\ifnotintoc\tableofcontents

这可以防止再次生成相同的标签(除非\newtest在重置测试计数器后再次使用!)

在此阶段,使用(需要包)ToC提取已写好的标签。(A用法也可以,但如果另外使用,则会有一个超链接)。\getrefnumberrefcount\refhyperref

\notintoctrue后面一定要說清楚\tableofcontents

\documentclass{article}


\usepackage{refcount}
\usepackage[bookmarksopen,bookmarksopenlevel=3]{hyperref}

\newcounter{test}

\makeatletter

\newif\ifnotintoc

\DeclareRobustCommand{\newtest}[1]{%
  \ifnotintoc
  \refstepcounter{test}\label{test:#1}% 
  Test \thetest\ #1%
  \else
  Test \getrefnumber{test:#1}\ #1%
  \fi
}

\g@addto@macro{\tableofcontents}{\addtocontents{toc}{\protect\global\protect\notintocfalse}}
\makeatother



\begin{document}

   \title{Test example}

   \maketitle

   \clearpage

   \tableofcontents
   \notintoctrue
   \clearpage

   \section{Design tests}
   \subsection{\newtest{A test}}
   \subsection{\newtest{Another test}}
   \section{Functional tests}
   \subsection{\newtest{Yet another test}}
 \end{document}

在此处输入图片描述

在此处输入图片描述

在此处输入图片描述

答案2

这可以通过重置旁边的计数器来实现Table of Contents

   \tableofcontents
   \setcounter{test}{0}

相关内容