Skip to content

Commit b04f625

Browse files
author
Manuel Mujica
committed
Account for existing ids when creating pretty anchors
1 parent 953bdef commit b04f625

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

static/docjs.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,26 @@ require("./styles/styles.less");
44

55
$(function() {
66
var headings = {};
7+
var collected = collectHeadings();
78

8-
collectHeadings().each(function() {
9+
collected.each(function() {
10+
var $el = $(this);
11+
var id = $el.attr("id");
12+
13+
if (id) headings[id] = true;
14+
});
15+
16+
17+
collected.each(function() {
918
var $el = $(this);
1019
var id = $el.attr("id");
1120

1221
if (!id) {
1322
id = makeAnchorHeadingId($el.text());
14-
var count = headings[id] || 0;
23+
var token = getUniqueToken(id, headings);
1524

16-
id += (count > 0) ? "-" + count : "";
17-
headings[id] = count + 1;
25+
id += (token > 0) ? "-" + token : "";
26+
headings[id] = true;
1827

1928
$el.attr("id", id);
2029
}
@@ -31,6 +40,18 @@ $(function() {
3140
}
3241
}
3342

43+
function getUniqueToken(id, headings) {
44+
var token = 0;
45+
var uniq = id;
46+
47+
while (headings[uniq]) {
48+
token += 1;
49+
uniq = id + "-" + token;
50+
}
51+
52+
return token;
53+
}
54+
3455
function collectHeadings() {
3556
return $(".content .comment h2, .content .comment h3");
3657
}

0 commit comments

Comments
 (0)