AnchorJS Dynamic Table of Contents

An example of how to make a dynamic table of contents using AnchorJS.

HTML

<script src="https://rawgit.com/bryanbraun/anchorjs/master/anchor.min.js"></script>
<div id="table-of-contents">
</div>

<section class="main centreGrid">
    <div class="articleList grid_Bg partBomMg grid_pd partTopMg">
        <div class="articleBox articleInfo ">
            <div class="articleTitle">加上爬虫的统计功能</div>
            <div class="articleType row">
                <i class="iconfont icon-Originality"></i>
                <span class="textColor1">2018-01-30</span>
                <p class="textColor1 classifyLabel">分类 <a href="http://127.0.0.1:8080/category/search-engine/index.html" class="textColor2">爬</a></p></div>
        </div>
        <div class="markdown-body" id="context">
            <p>[{menu}]</p>
<h3 id="h3--dubbo-"><a name="什么是dubbo?" class="reference-link"></a><span class="header-link octicon octicon-link"></span>什么是dubbo?</h3><h4 id="h4-u80CCu666F"><a name="背景" class="reference-link"></a><span class="header-link octicon octicon-link"></span>背景</h4><p>随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,亟需一个治理系统确保架构有条不紊的演进。</p>
<blockquote>
<p>单一应用架构</p>
</blockquote>
<p>当网站流量很小时,只需一个应用,将所有功能都部署在一起,以减少部署节点和成本。此时,用于简化增删改查工作量的数据访问框架(ORM)是关键。</p>
<p><img src="https://static.zixu.hk/liaozixu.com/app/cms/file/20180812/053831/ef21ac0848bf4b80b853f191d0cb7ad0.png" alt="">
<blockquote>
<p>垂直应用架构</p>
</blockquote>
<p>当访问量逐渐增大,单一应用增加机器带来的加速度越来越小,将应用拆成互不相干的几个应用,以提升效率。此时,用于加速前端页面开发的Web框架(MVC)是关键。</p>
<p><img src="https://static.zixu.hk/liaozixu.com/app/cms/file/20180812/054154/21964f111bbb4c84a8af343e2666329e.png" alt="">
<blockquote>
<p>分布式服务架构</p>
</blockquote>
<p>当垂直应用越来越多,应用之间交互不可避免,将核心业务抽取出来,作为独立的服务,逐渐形成稳定的服务中心,使前端应用能更快速的响应多变的市场需求。此时,用于提高业务复用及整合的分布式服务框架(RPC)是关键。</p>
<p><img src="https://static.zixu.hk/liaozixu.com/app/cms/file/20180812/054627/4b0c59e1389b46c489faa16ca48dcc9e.png"...

JavaScript

anchors.options.visible = 'always';
anchors.add('h2');
console.log(anchors.elements)
generateTableOfContents(anchors.elements);

// External code for generating a simple dynamic Table of Contents
function generateTableOfContents(els) {
	var anchoredElText,
  		anchoredElHref,
			ul = document.createElement('UL');

  document.getElementById('table-of-contents').appendChild(ul);

	for (var i = 0; i < els.length; i++) {
  	anchoredElText = els[i].textContent;
		anchoredElHref = els[i].querySelector('.anchorjs-link').getAttribute('href');
  	addNavItem(ul, anchoredElHref, anchoredElText);
  }
}

function addNavItem(ul, href, text) {
  var listItem = document.createElement('LI'),
		  anchorItem = document.createElement('A'),
  	  textNode = document.createTextNode(text);
  
  anchorItem.href = href;
  ul.appendChild(listItem);
  listItem.appendChild(anchorItem);
  anchorItem.appendChild(textNode);
}