重复计数器导致超链接错误

重复计数器导致超链接错误

我遇到了一个有趣的问题hyperref。显然,当计数器重置时,它\setcounter{mycounter}{0}总是hyperref链接到计数器的第一个可能实例,而不是相应标签所在的实例。

查看此 MWE:

% !TEX TS-program = xelatexmk
\documentclass{article}
\usepackage[paperwidth=6in,paperheight=3in]{geometry}
\usepackage{hyperref}
\hypersetup{colorlinks=true, allcolors=blue, }
\newcounter{mycounter}\setcounter{mycounter}{0}
\newcommand\countme{\refstepcounter{mycounter}\themycounter}

\begin{document} 
First line \countme{} has some interesting text.

The second line \countme \label{onelabel} has \textbf{more} interesting text.

As we saw at line \ref{onelabel} ...

\newpage 
A new page brings new numbers \setcounter{mycounter}{0} 

A very different first line \countme{} has other interesting text.

The second line \countme \label{otherlabel} has \textbf{different} interesting text.

As we saw at line \ref{otherlabel} ...
\end{document}

正如您在下面的屏幕截图中看到的,第二页上的弹出预览\ref不是指第二行,\label{otherlabel}而是指第一页上的一行(在 TeXShop 中也有工具提示“转到第 1 页”)。我是不是对 的基本知识不理解hyperref

在此处输入图片描述

所有这些的上下文都是一个在开始时将我的计数器重置为 0 的环境。并且\refs环境的第二或第三次迭代中所有后续标签都指向该环境的第一个实例,而不是标签所在的正确实例。

答案1

hyperref 使用 \themycounter 为链接创建锚点。如果出现两次相同的 \themycounter 值,就会出现问题。在这种情况下,您必须定义 \theHmycounter,以便它提供唯一的目标名称:

\documentclass{article}
\usepackage[paperwidth=6in,paperheight=3in]{geometry}
\usepackage{hyperref}
\hypersetup{colorlinks=true, allcolors=blue, }
\newcounter{mycounter}\setcounter{mycounter}{0}
\newcommand\countme{\refstepcounter{mycounter}\themycounter}

\begin{document}
First line \countme{} has some interesting text.

The second line \countme \label{onelabel} has \textbf{more} interesting text.

As we saw at line \ref{onelabel} ...

\newpage
A new page brings new numbers \setcounter{mycounter}{0} 
\renewcommand\theHmycounter{sec.\themycounter} %unique prefix

A very different first line \countme{} has other interesting text.

The second line \countme \label{otherlabel} has \textbf{different} interesting text.

As we saw at line \ref{otherlabel} ...
\end{document}

相关内容