我尝试在目录中的节行下添加超链接,但尝试时出现编译错误。如果取消注释注释行,则以下代码将无法编译。有解决方案吗?
\documentclass{article}
\usepackage{hyperref, color}
\def\animal{zebra}
\def\mylabel{zzz}
\begin{document}
\tableofcontents
\section{Zoo}
%\addtocontents{toc}{\hyperlink{\mylabel}{\textcolor{blue}{\animal}}}
\addtocontents{toc}{\textcolor{blue}{\animal}}
\hypertarget{\mylabel}{\noindent Here is a zebra.} \\
Go to \hyperlink{\mylabel}{\textcolor{blue}{\animal}}.
\end{document}
答案1
对于您的情况,您需要\protect
添加\hyperlink
:
\addtocontents{toc}{\protect\hyperlink{\mylabel}{\textcolor{blue}{\animal}}}
% ^^^^^^^^
使用以下 MWE
\documentclass{article}
\usepackage{color}
\usepackage{hyperref} % <================= should be last called package
\def\animal{zebra}
\def\mylabel{zzz}
\begin{document}
\tableofcontents
\section{Zoo}
\addtocontents{toc}{\protect\hyperlink{\mylabel}{\textcolor{blue}{\animal}}}
%\addtocontents{toc}{\textcolor{blue}{\animal}}
\hypertarget{\mylabel}{\noindent Here is a zebra.} \\
Go to \hyperlink{\mylabel}{\textcolor{blue}{\animal}}.
\end{document}
你得到了想要的结果: