自动目录(TOC)

时间:2014-05-13 17:48:06

标签: javascript jquery frontend tableofcontents

我正在使用markdown文档构建一个网站。我想添加一个内容表,所以我需要自动转换这个HTML源代码(从markdown自动呈现):

的src:

<div id="content">
  <h1>Article title</h1>
  <h2>example header 1</h2>
  <h2>example header 2</h2>
  <h2>example header 3</h2>
  <h3>example sub-header 1</h3>
  <h3>example sub-header 2</h3>
</div>

DEST:

<div id="content">
  <h1 id="article-title">Article title</h1>
  <h2 id="example-header-1">example header 1</h2>
  <h2 id="example-header-2">example header 2</h2>
  <h2 id="example-header-3">example header 3</h2>
  <h3 id="example-sub-header-1">example sub-header 1</h3>
  <h3 id="example-sub-header-2">example sub-header 2</h3>
</div>
<div id="toc">
  <p>Article title</p>
  <ul>
    <li><a href="#example-header-1">example header 1</a></li>
    <li><a href="#example-header-2">example header 2</a></li>
    <li><a href="#example-header-3">example header 3</a></li>
    <li>
      <ul>
        <li><a href="#example-sub-header-1">example sub-header 1</a></li>
        <li><a href="#example-sub-header-2">example sub-header 2</a></li>
      </ul>
    </li>
    </li><a href="#content">Back to top</a></li>
  </ul>
</div>

我已经完成了jQuery的部分工作,但我是一个菜鸟,我不能继续:

// Append "Back to top" button to TOC element
$("#toc ul").append(
  "<p>" + $('#doc h1:first').text() + "</p>"
);

// automatic table of content generation
$("#doc h2").each(function() {
  // Add automatic ID for each heading element
  var header = $(this).text();
  var anchor = header
    .toLowerCase()
    .replace(/[^a-z0-9\s]/gi, '')
    .replace(/[_\s]/g, '-');
  $(this).attr("id", anchor);
  // Create TOC
  $("#toc ul").append(
    "<li><a href='#" + anchor + "'>" + header + "</a></li>"
  );
});

// Append "Back to top" button to TOC element
$("#toc ul").append(
  "<li><a href='#top'>Back to top</a></li>"
);

有人可以帮我完成这个吗?

0 个答案:

没有答案