JavaScript で以下のような TOC を生成したいと思います。
<ol>
<li>Heading 1</li>
<li>Heading 2
<ol>
<li>Heading 2-1</li>
<li>Heading 2-2</li>
</ol>
</li>
<li>Heading 3</li>
</ol>
そして、上記の目次を生成するための HTML コード:
<section id="toc">
<p>This will be replaced with generated TOC.
</section>
<article>
<h1>Heading 1<h1>
<p>Bla bla bla.</p>
<h1>Heading 2<h1>
<p>Bla bla bla.</p>
<h2>Heading 2-1<h2>
<p>Bla bla bla.</p>
<h2>Heading 2-2<h2>
<p>Bla bla bla.</p>
<h1>Heading 3<h1>
<p>Bla bla bla.</p>
</article>
私は本当に立ち往生しています :( TOC を生成するコードをどのように記述しますか?私は jQuery または純粋な JavaScript を好みます。
アップデート
これは私にとってかなり大変でしたが、どういうわけか私はやったと思います:
$(function () {
var assigned_level = 0,
current_level = 0,
id_number = 1,
parent_node = "article",
toc_html = '';
$(parent_node + " *").each(function () {
if (this.nodeName.length === 2 && this.nodeName.charAt(0) === "H") {
$(this).attr("class", "heading");
}
});
$(".heading").each( function () {
current_level = this.nodeName.charAt(1);
$(this).attr('id', "toc-" + id_number);
// Close a list if a same level list follows.
if (assigned_level !== current_level - 1) {
toc_html += "</li>"
}
// Open parent lists if a child list follows.
while (assigned_level < current_level) {
toc_html += "<ol>";
assigned_level += 1;
}
// Close child lists and the parent list if
// the same level parent list follows.
while (assigned_level > current_level) {
toc_html += "</ol></li>";
assigned_level -= 1;
}
toc_html +=
'<li><a href="#' + this.id + '">' + $(this).html() + "</a>";
id_number += 1;
});
// Close everything
while (assigned_level > 0) {
toc_html += "</li></ol>";
assigned_level -= 1;
}
$("#toc").html(toc_html);
});
私は自分が何をしたのかまだ理解していません:P おそらくもっと洗練された方法があるでしょう. 見つけたものは何でも指摘してください。
ありがとう。