1

我正在寻找这样的脚本,但找不到。有很多 TOC 生成器,但它们都是平面或伪多级 - 例如它们基于 H1、H2 标签中的数字。

我有一个简单的嵌套 HTML 结构,例如:

 <div class="toc"><div class="toc_target" id="ch1">Chapter 1</div></div>
 <div class="toc"><div class="toc_target" id="ch2">Chapter 2</div></div>
 <div class="toc"><div class="toc_target" id="ch3">Chapter 3</div>
     <div class="toc"><div class="toc_target" id="ch31">Chapter 31</div>
 </div>
 <div class="toc"><div class="toc_target" id="ch4">Chapter 4</div>
     <div class="toc"><div class="toc_target" id="ch41">Chapter 41</div>
         <div class="toc"><div class="toc_target" id="ch411">Chapter 411</div>
     </div>
 </div>

...并且需要一个带有内部链接的目录,自动编号(HTML 结构可能是扁平的或嵌套的):

1. 第 1 章
2.第2章
3.第3章
3.1。第31章
4.第4章
4.1。第41章
4.1.1。第411章

有人吗?

4

1 回答 1

0

看来我必须一个人去战斗……

    function getLastNumberFromTocId(tocId) {
    if (tocId.length==0) return "";
    arr=tocId.split(".");
    return parseInt(arr[arr.length-2]); 
}



/*
Generates TOC.
Attribute "toc_id" is added to each node in content to store its numbering. It is used later to calculate the children's numbering.
First ideas from http://monochromacy.net/Post/Dynamic-Section-Numbers-and-Table-of-Contents-with-jQuery.aspx.
*/
function generateTableOfContents(list) {
var tocHtml = '';
list.each(function() {
        var current = $(this);

        // calculation of actual chapter number ()
        parentElement = current.parents(".toc");
        parentElementTocId = "";

        if (parentElement.size() == 1) parentElementTocId = parentElement.attr("toc_id");
        if (typeof  parentElementTocId === "undefined") parentElementTocId = "";

        previousTocId = "0.";
        previousToc = current.prev(".toc");
        if (previousToc.size() == 1) previousTocId = previousToc.attr("toc_id");

        localNumber = getLastNumberFromTocId(previousTocId) + 1;
        currentTocId = parentElementTocId + localNumber + ".";

        // store the result
        current.attr("toc_id", currentTocId);


        var headerElement = current.find(".toc-title").first();
        // text to be displayed
        headerElement.prepend(currentTocId + " ");
        var tocEntryText = headerElement.text();

        // get the link target
        var tocEntryId = headerElement.attr("id");
        tocHtml += '<span class="toc-entry"><a href="#' + tocEntryId + '">'  + tocEntryText + '</a></span>\n';
    });
return tocHtml;

}

于 2012-09-02T16:47:05.297 回答